sys.byteorder

Here are the examples of the python api sys.byteorder taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

87 Examples 7

Page 1 Selected Page 2

Example 1

Project: talk.org Source File: decoder.py
Function: floatconstants
def _floatconstants():
    import struct
    import sys
    _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
    if sys.byteorder != 'big':
        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
    nan, inf = struct.unpack('dd', _BYTES)
    return nan, inf, -inf

Example 2

Project: bh2014 Source File: utf_32.py
    def encode(self, input, errors='strict'):
        if self.encoder is None:
            result = codecs.utf_32_encode(input, errors)
            if sys.byteorder == 'little':
                self.encoder = codecs.utf_32_le_encode
            else:
                self.encoder = codecs.utf_32_be_encode
            return result
        else:
            return self.encoder(input, errors)

Example 3

Project: ironpython3 Source File: test_byteswap.py
Function: test_endian_float
    def test_endian_float(self):
        if sys.byteorder == "little":
            self.assertIs(c_float.__ctype_le__, c_float)
            self.assertIs(c_float.__ctype_be__.__ctype_le__, c_float)
        else:
            self.assertIs(c_float.__ctype_be__, c_float)
            self.assertIs(c_float.__ctype_le__.__ctype_be__, c_float)
        s = c_float(math.pi)
        self.assertEqual(bin(struct.pack("f", math.pi)), bin(s))
        # Hm, what's the precision of a float compared to a double?
        self.assertAlmostEqual(s.value, math.pi, places=6)
        s = c_float.__ctype_le__(math.pi)
        self.assertAlmostEqual(s.value, math.pi, places=6)
        self.assertEqual(bin(struct.pack("<f", math.pi)), bin(s))
        s = c_float.__ctype_be__(math.pi)
        self.assertAlmostEqual(s.value, math.pi, places=6)
        self.assertEqual(bin(struct.pack(">f", math.pi)), bin(s))

Example 4

Project: ljd Source File: constants.py
def _assemble_number(lo, hi):
	if sys.byteorder == 'big':
		float_as_int = lo << 32 | hi
	else:
		float_as_int = hi << 32 | lo

	raw_bytes = struct.pack("=Q", float_as_int)
	return struct.unpack("=d", raw_bytes)[0]

Example 5

Project: pyrf Source File: vrt.py
Function: update_data
    def _update_data(self):
        self._data = array.array({
            1: 'b',
            2: 'h',
            4: 'l' if array.array('l').itemsize == 4 else 'i',
            }[self._bytes_per_sample])
        self._data.fromstring(self._strdata)
        if self._bytes_per_sample > 1 and sys.byteorder == 'little':
            self._data.byteswap()

Example 6

Project: redis-rdb-tools Source File: callbacks.py
Function: floatconstants
def _floatconstants():
    _BYTES = b'\x7F\xF8\x00\x00\x00\x00\x00\x00\x7F\xF0\x00\x00\x00\x00\x00\x00'
    # The struct module in Python 2.4 would get frexp() out of range here
    # when an endian is specified in the format string. Fixed in Python 2.5+
    if sys.byteorder != 'big':
        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
    nan, inf = struct.unpack('dd', _BYTES)
    return nan, inf, -inf

Example 7

Project: keymaker Source File: __init__.py
def aws_to_unix_id(aws_key_id):
    """Converts a AWS Key ID into a UID"""
    uid_bytes = hashlib.sha256(aws_key_id.encode()).digest()[-2:]
    if USING_PYTHON2:
        return 2000 + int(from_bytes(uid_bytes) // 2)
    else:
        return 2000 + (int.from_bytes(uid_bytes, byteorder=sys.byteorder) // 2)

Example 8

Project: babble Source File: utf_16.py
    def encode(self, input, errors='strict'):
        self.bom_written = True
        result = codecs.utf_16_encode(input, errors)
        if sys.byteorder == 'little':
            self.encode = codecs.utf_16_le_encode
        else:
            self.encode = codecs.utf_16_be_encode
        return result

Example 9

Project: splash Source File: qtrender_image.py
    def qimage_to_pil_image(self, qimage):
        """Convert QImage (in ARGB32 format) to PIL.Image (in RGBA mode)."""
        # In our case QImage uses 0xAARRGGBB format stored in host endian order,
        # we must convert it to [0xRR, 0xGG, 0xBB, 0xAA] sequences used by
        # Pillow.
        buf = qimage.bits().asstring(qimage.byteCount())
        if sys.byteorder != "little":
            buf = self.swap_byte_order_i32(buf)
        # PIL>2.0 doesn't have fromstring. But older ones don't have frombytes.
        if hasattr(Image, 'frombytes'):
            frombytes = Image.frombytes
        else:
            frombytes = Image.fromstring

        return frombytes(
            self.pillow_image_format,
            self._qsize_to_tuple(qimage.size()),
            buf, 'raw', self.pillow_decoder_format)

Example 10

Project: ryu Source File: pcaplib.py
Function: serialize
    def serialize(self):
        if sys.byteorder == 'big':
            # Big Endian
            fmt = self._FILE_HDR_FMT_BIG_ENDIAN
            self.magic = self.MAGIC_NUMBER_IDENTICAL
        else:
            # Little Endian
            fmt = self._FILE_HDR_FMT_LITTLE_ENDIAN
            self.magic = self.MAGIC_NUMBER_SWAPPED

        return struct.pack(fmt, self.magic, self.version_major,
                           self.version_minor, self.thiszone,
                           self.sigfigs, self.snaplen, self.network)

Example 11

Project: databus Source File: utf_32.py
    def getstate(self):
        # additonal state info from the base class must be None here,
        # as it isn't passed along to the caller
        state = codecs.BufferedIncrementalDecoder.getstate(self)[0]
        # additional state info we pass to the caller:
        # 0: stream is in natural order for this platform
        # 1: stream is in unnatural order
        # 2: endianness hasn't been determined yet
        if self.decoder is None:
            return (state, 2)
        addstate = int((sys.byteorder == "big") !=
                       (self.decoder is codecs.utf_32_be_decode))
        return (state, addstate)

Example 12

Project: python-compat-runtime Source File: _remote_socket_addr.py
def ntohs(integer):
  """ntohs(integer) -> integer

  Convert a 16-bit integer from network to host byte order.
  """
  if sys.byteorder == 'big':
    return integer
  if not isinstance(integer, (int, long)):
    raise TypeError('an integer is required')
  if integer < 0:
    raise OverflowError("can't convert negative number to unsigned long")
  if integer >= (1<<16):
    raise OverflowError('signed integer is greater than maximum')
  return int(
      ((integer&0xff00)>>8)|
      ((integer&0x00ff)<<8))

Example 13

Project: psd-tools Source File: utils.py
def fix_byteorder(arr):
    """
    Fixes the byte order of the array (assuming it was read
    from a Big Endian data).
    """
    if sys.byteorder == 'little':
        arr.byteswap()
    return arr

Example 14

Project: ssp Source File: core.py
def HTKSource(fileName, native=False):
    fmt = '>iihh'
    if native:
        fmt = 'iihh'
    with open(fileName, 'r') as f:
        # The resulting array here is float32.  We could explicitly
        # cast it to double, but that will happen further up in the
        # program anyway.
        header = f.read(12)
        (htkSize, htkPeriod, htkVecSize, htkKind) = unpack(fmt, header)
        data = np.fromfile(f, dtype='f')
        a = data.reshape((htkSize, htkVecSize / 4))
        if ((not native) and (sys.byteorder == 'little')):
            a = a.byteswap()
    return a, htkPeriod * 1e-7

Example 15

Project: pygame_sdl2 Source File: arrinter.py
    def test_byteswapped(self):
        a = Array((1,), 'u', 4, flags=(PAI_ALIGNED | PAI_WRITEABLE))
        ct = a._ctype
        self.assertTrue(ct is not c_uint32)
        if sys.byteorder == 'little':
            self.assertTrue(ct is c_uint32.__ctype_be__)
        else:
            self.assertTrue(ct is c_uint32.__ctype_le__)
        i = 0xa0b0c0d
        n = c_uint32(i)
        a[0] = i
        self.assertEqual(a[0], i)
        self.assertEqual(a._data[0:4],
                         cast(addressof(n), POINTER(c_uint8))[3:-1:-1])

Example 16

Project: dpkt Source File: pcap.py
Function: write_pkt
    def writepkt(self, pkt, ts=None):
        if ts is None:
            ts = time.time()
        s = str(pkt)
        n = len(s)
        if sys.byteorder == 'little':
            ph = LEPktHdr(tv_sec=int(ts),
                          tv_usec=int(round(ts % 1, self._precision) * 10 ** self._precision),
                          caplen=n, len=n)
        else:
            ph = PktHdr(tv_sec=int(ts),
                        tv_usec=int(round(ts % 1, self._precision) * 10 ** self._precision),
                        caplen=n, len=n)
        self.__f.write(str(ph))
        self.__f.write(s)

Example 17

Project: Django-facebook Source File: utf_16.py
    def encode(self, input, final=False):
        if self.encoder is None:
            result = codecs.utf_16_encode(input, self.errors)[0]
            if sys.byteorder == 'little':
                self.encoder = codecs.utf_16_le_encode
            else:
                self.encoder = codecs.utf_16_be_encode
            return result
        return self.encoder(input, self.errors)[0]

Example 18

Project: pyhwp Source File: dataio.py
def decode_uint16le_array_default(bytes):
    from array import array
    codes = array('H', bytes)
    if sys.byteorder == 'big':
        codes.byteswap()
    return codes

Example 19

Project: autotest Source File: decoder.py
Function: floatconstants
def _floatconstants():
    _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
    # The struct module in Python 2.4 would get frexp() out of range here
    # when an endian is specified in the format string. Fixed in Python 2.5+
    if sys.byteorder != 'big':
        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
    nan, inf = struct.unpack('dd', _BYTES)
    return nan, inf, -inf

Example 20

Project: pyon Source File: ion_time.py
    @staticmethod
    def htonl(val):
        import sys
        val = np.uint32(val)
        if sys.byteorder == 'little':
            return val.byteswap()
        return val

Example 21

Project: yos-social-python Source File: decoder.py
Function: floatconstants
def _floatconstants():
    import struct
    import sys
    _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
    if sys.byteorder != 'big':
        # NOTE(kgibbs): These lines must be added to make this file work under
        # Python 2.2, which is commonly used at Google.
        bytes_list = list(_BYTES)
        bytes_first_half = bytes_list[:8]; bytes_first_half.reverse()
        bytes_second_half = bytes_list[8:]; bytes_second_half.reverse()
        _BYTES = "".join(bytes_first_half + bytes_second_half)
        # NOTE(kgibbs): End changes.
    nan, inf = struct.unpack('dd', _BYTES)
    return nan, inf, -inf

Example 22

Project: bde-tools Source File: bde_printer.py
Function: to_string
    def to_string(self):
        value = long(self.val['d_value'])
        if value < 0:
            value += 2L ** 64
        invalid = (value & Datetime.REP_MASK) == 0
        if invalid:
            if sys.byteorder == "little":
                days = (value & Datetime.MASK_32) - 1
                milliseconds = value >> Datetime.SHIFT_32
            else:
                days = (value >> Datetime.SHIFT_32) - 1
                milliseconds = value & Datetime.MASK_32
            value = (days << Datetime.TIME_BITS) | (1000L * milliseconds)
        else:
            value ^= Datetime.REP_MASK
        date = Date.toYMD((value >> Datetime.TIME_BITS) + 1)
        time = Time.toHMuS(value & Datetime.TIME_MASK)

        return "%s%sT%s" % (("[invalid]" if invalid else ""), date, time)

Example 23

Project: PyClassLessons Source File: geometries.py
    @property
    def wkb(self):
        "Returns the WKB representation of the Geometry."
        if sys.byteorder == 'little':
            byteorder = 1  # wkbNDR (from ogr_core.h)
        else:
            byteorder = 0  # wkbXDR
        sz = self.wkb_size
        # Creating the unsigned character buffer, and passing it in by reference.
        buf = (c_ubyte * sz)()
        capi.to_wkb(self.ptr, byteorder, byref(buf))
        # Returning a buffer of the string at the pointer.
        return memoryview(string_at(buf, sz))

Example 24

Project: flappy-bird-py Source File: quicktime.py
Function: get_formats
    def _get_formats(self):
        # TODO choose 24 bit where appropriate.
        if sys.byteorder == 'big':
            format = 'ARGB'
            qtformat = k32ARGBPixelFormat
        else:
            format = 'BGRA'
            qtformat = k32BGRAPixelFormat
        return format, qtformat

Example 25

Project: WPA2-HalfHandshake-Crack Source File: pcapParser.py
Function: init
    def __init__(self, header, packets=None):
        if not packets:
            packets = []
        self.header = header
        self.packets = packets
        self.valid = None
        self.byteorder = sys.byteorder

        if not self.__validate__():
            self.valid = False
        else:
            self.valid = True

        assert self.valid, 'Invalid savefile.'

Example 26

Project: pwnypack Source File: target.py
Function: init
    def __init__(self, arch=None, bits=None, endian=None, mode=0):
        if arch is None:
            arch = self._DEFAULT_ARCH.get(platform.machine(), Target.Arch.unknown)

            if bits is None:
                bits = Target.Bits(64 if platform.architecture()[0] == '64bit' else 32)

            if endian is None:
                endian = Target.Endian.__members__[sys.byteorder]

        self.arch = arch
        self.bits = bits
        self.endian = endian
        self.mode = mode

Example 27

Project: simian Source File: _remote_socket_addr.py
def ntohl(integer):
  """ntohl(integer) -> integer

  Convert a 32-bit integer from network to host byte order.
  """
  if sys.byteorder == 'big':
    return integer
  if not isinstance(integer, (int, long)):
    raise TypeError('expected int/long, %s found' % _TypeName(integer))
  if integer < 0:
    raise OverflowError('can\'t convert negative number to unsigned long')
  if integer >= (1<<32):
    raise OverflowError('long int larger than 32 bits')
  return int(
      ((integer&0xff000000)>>24)|
      ((integer&0x00ff0000)>>8)|
      ((integer&0x0000ff00)<<8)|
      ((integer&0x000000ff)<<24))

Example 28

Project: dogeon Source File: _compact.py
def _floatconstants():
    if PY2:
        _bytes = _BYTES.decode('hex')
    else:
        import codecs
        _bytes = codecs.decode(_BYTES, 'hex_codec')
    if sys.byteorder != 'big':
        _bytes = _bytes[:8][::-1] + _bytes[8:][::-1]
    nan, inf = struct.unpack('dd', _bytes)
    return nan, inf, -inf

Example 29

Project: moul-scripts Source File: utf_16.py
    def encode(self, input, errors='strict'):
        if self.encoder is None:
            result = codecs.utf_16_encode(input, errors)
            if sys.byteorder == 'little':
                self.encoder = codecs.utf_16_le_encode
            else:
                self.encoder = codecs.utf_16_be_encode
            return result
        else:
            return self.encoder(input, errors)

Example 30

Project: watchdog Source File: decoder.py
Function: floatconstants
def _floatconstants():
    _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
    if sys.byteorder != 'big':
        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
    nan, inf = struct.unpack('dd', _BYTES)
    return nan, inf, -inf

Example 31

Project: openwrt-mt7620 Source File: test_byteswap.py
Function: test_endian_float
    def test_endian_float(self):
        if sys.byteorder == "little":
            self.assertTrue(c_float.__ctype_le__ is c_float)
            self.assertTrue(c_float.__ctype_be__.__ctype_le__ is c_float)
        else:
            self.assertTrue(c_float.__ctype_be__ is c_float)
            self.assertTrue(c_float.__ctype_le__.__ctype_be__ is c_float)
        s = c_float(math.pi)
        self.assertEqual(bin(struct.pack("f", math.pi)), bin(s))
        # Hm, what's the precision of a float compared to a double?
        self.assertAlmostEqual(s.value, math.pi, 6)
        s = c_float.__ctype_le__(math.pi)
        self.assertAlmostEqual(s.value, math.pi, 6)
        self.assertEqual(bin(struct.pack("<f", math.pi)), bin(s))
        s = c_float.__ctype_be__(math.pi)
        self.assertAlmostEqual(s.value, math.pi, 6)
        self.assertEqual(bin(struct.pack(">f", math.pi)), bin(s))

Example 32

Project: splunk-webframework Source File: geometries.py
    @property
    def wkb(self):
        "Returns the WKB representation of the Geometry."
        if sys.byteorder == 'little':
            byteorder = 1 # wkbNDR (from ogr_core.h)
        else:
            byteorder = 0 # wkbXDR
        sz = self.wkb_size
        # Creating the unsigned character buffer, and passing it in by reference.
        buf = (c_ubyte * sz)()
        wkb = capi.to_wkb(self.ptr, byteorder, byref(buf))
        # Returning a buffer of the string at the pointer.
        return memoryview(string_at(buf, sz))

Example 33

Project: volumina Source File: imagesources_test.py
    def testRequest( self ):
        imr = self.ims.request(QRect(0,0,512,512))
        result = imr.wait()
        self.assertTrue(type(result) == QImage)

        result_view = qimage2ndarray.byte_view(result)
        if sys.byteorder == "little":
            self.assertTrue((result_view[:1, :, 3] == 0).all())
            self.assertTrue((result_view[-1:, :, 3] == 0).all())
            self.assertTrue((result_view[:, :1, 3] == 0).all())
            self.assertTrue((result_view[:, -1:, 3] == 0).all())
        else:
            self.assertTrue((result_view[:1, :, 0] == 0).all())
            self.assertTrue((result_view[-1:, :, 0] == 0).all())
            self.assertTrue((result_view[:, :1, 0] == 0).all())
            self.assertTrue((result_view[:, -1:, 0] == 0).all())

Example 34

Project: HealthStarter Source File: utf_32.py
    def setstate(self, state):
        if state:
            self.encoder = None
        else:
            if sys.byteorder == 'little':
                self.encoder = codecs.utf_32_le_encode
            else:
                self.encoder = codecs.utf_32_be_encode

Example 35

Project: SwiftKitten Source File: test_ffi_obj.py
def test_memmove():
    ffi = _cffi1_backend.FFI()
    p = ffi.new("short[]", [-1234, -2345, -3456, -4567, -5678])
    ffi.memmove(p, p + 1, 4)
    assert list(p) == [-2345, -3456, -3456, -4567, -5678]
    p[2] = 999
    ffi.memmove(p + 2, p, 6)
    assert list(p) == [-2345, -3456, -2345, -3456, 999]
    ffi.memmove(p + 4, ffi.new("char[]", b"\x71\x72"), 2)
    if sys.byteorder == 'little':
        assert list(p) == [-2345, -3456, -2345, -3456, 0x7271]
    else:
        assert list(p) == [-2345, -3456, -2345, -3456, 0x7172]

Example 36

Project: Shapely Source File: base.py
    @property
    def array_interface_base(self):
        if sys.byteorder == 'little':
            typestr = '<f8'
        elif sys.byteorder == 'big':
            typestr = '>f8'
        else:
            raise ValueError(
                "Unsupported byteorder: neither little nor big-endian")
        return {
            'version': 3,
            'typestr': typestr,
            'data': self.ctypes,
            }

Example 37

Project: kbengine Source File: test_byteswap.py
    @unittest.skip('test disabled')
    def test_X(self):
        print(sys.byteorder, file=sys.stderr)
        for i in range(32):
            bits = BITS()
            setattr(bits, "i%s" % i, 1)
            dump(bits)

Example 38

Project: imagrium Source File: test_hash.py
    def test_fixed_hash(self):
        # test a fixed seed for the randomized hash
        # Note that all types share the same values:
        if IS_64BIT:
            if sys.byteorder == 'little':
                h = -4410911502303878509
            else:
                h = -3570150969479994130
        else:
            if sys.byteorder == 'little':
                h = -206076799
            else:
                h = -1024014457
        self.assertEqual(self.get_hash(self.repr_, seed=42), h)

Example 39

Project: hashmoji Source File: hashmoji.py
def _findmoji(the_bytes):
    """
    Look up an emoji based on ``BYTE_SIZE``.
    """
    if len(the_bytes) != 4:
        raise InvalidByteLength("{0} is {1} bytes not {2}.".format(the_bytes, len(the_bytes), BYTE_SIZE))
    index = int.from_bytes(the_bytes, sys.byteorder, signed=False)
    # Normalize the index to a floating point number between 0 and 1.
    normalized_index = index / MAX_INT
    # Spread results between 0 and 842.
    final_index = normalized_index * 842 + 1;
    # Group result buckets by integer.
    return _lookup(int(final_index))

Example 40

Project: xcffib Source File: test_python_code.py
    def test_union_pack(self):
        data = struct.pack("=" + ("b" * 20), *range(20))
        cffi_data = xcffib.ffi.new('char[]', data)

        cm = xcffib.xproto.ClientMessageData(xcffib.CffiUnpacker(cffi_data))

        for actual, expected in zip(range(20), cm.data8):
            assert actual == expected, actual

        if sys.byteorder == "little":
            assert cm.data32[0] == 0x03020100
            assert cm.data32[1] == 0x07060504
            assert cm.data32[2] == 0x0b0a0908
        elif sys.byteorder == "big":
            assert cm.data32[0] == 0x00010203
            assert cm.data32[1] == 0x04050607
            assert cm.data32[2] == 0x08090a0b
        else:
            raise Exception("unknown byte order?")

Example 41

Project: neuroConstruct Source File: utf_16.py
    def setstate(self, state):
        if state:
            self.encoder = None
        else:
            if sys.byteorder == 'little':
                self.encoder = codecs.utf_16_le_encode
            else:
                self.encoder = codecs.utf_16_be_encode

Example 42

Project: Django--an-app-at-a-time Source File: geometries.py
    @property
    def wkb(self):
        "Returns the WKB representation of the Geometry."
        if sys.byteorder == 'little':
            byteorder = 1  # wkbNDR (from ogr_core.h)
        else:
            byteorder = 0  # wkbXDR
        sz = self.wkb_size
        # Creating the unsigned character buffer, and passing it in by reference.
        buf = (c_ubyte * sz)()
        capi.to_wkb(self.ptr, byteorder, byref(buf))
        # Returning a buffer of the string at the pointer.
        return six.memoryview(string_at(buf, sz))

Example 43

Project: pyon Source File: ion_time.py
    @staticmethod
    def htonstr(val):
        import sys
        if sys.byteorder == 'little':
            l = len(val)
            nval = [0] * l
            for i in xrange(l/2):
                nval[i*2]  = val[l - i*2 - 2]
                nval[i*2+1]= val[l - i*2 - 1]
            return ''.join(nval)
        return val

Example 44

Project: Veil-Catapult Source File: test_byteswap.py
    def test_endian_double(self):
        if sys.byteorder == "little":
            self.assertTrue(c_double.__ctype_le__ is c_double)
            self.assertTrue(c_double.__ctype_be__.__ctype_le__ is c_double)
        else:
            self.assertTrue(c_double.__ctype_be__ is c_double)
            self.assertTrue(c_double.__ctype_le__.__ctype_be__ is c_double)
        s = c_double(math.pi)
        self.assertEqual(s.value, math.pi)
        self.assertEqual(bin(struct.pack("d", math.pi)), bin(s))
        s = c_double.__ctype_le__(math.pi)
        self.assertEqual(s.value, math.pi)
        self.assertEqual(bin(struct.pack("<d", math.pi)), bin(s))
        s = c_double.__ctype_be__(math.pi)
        self.assertEqual(s.value, math.pi)
        self.assertEqual(bin(struct.pack(">d", math.pi)), bin(s))

Example 45

Project: PokemonGo-Bot-Desktop Source File: utf_32.py
    def encode(self, input, final=False):
        if self.encoder is None:
            result = codecs.utf_32_encode(input, self.errors)[0]
            if sys.byteorder == 'little':
                self.encoder = codecs.utf_32_le_encode
            else:
                self.encoder = codecs.utf_32_be_encode
            return result
        return self.encoder(input, self.errors)[0]

Example 46

Project: pymo Source File: test_cast.py
    def test_array2pointer(self):
        array = (c_int * 3)(42, 17, 2)

        # casting an array to a pointer works.
        ptr = cast(array, POINTER(c_int))
        self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2])

        if 2*sizeof(c_short) == sizeof(c_int):
            ptr = cast(array, POINTER(c_short))
            if sys.byteorder == "little":
                self.assertEqual([ptr[i] for i in range(6)],
                                     [42, 0, 17, 0, 2, 0])
            else:
                self.assertEqual([ptr[i] for i in range(6)],
                                     [0, 42, 0, 17, 0, 2])

Example 47

Project: SickGear Source File: decoder.py
Function: floatconstants
def _floatconstants():
    _BYTES = fromhex('7FF80000000000007FF0000000000000')
    # The struct module in Python 2.4 would get frexp() out of range here
    # when an endian is specified in the format string. Fixed in Python 2.5+
    if sys.byteorder != 'big':
        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
    nan, inf = struct.unpack('dd', _BYTES)
    return nan, inf, -inf

Example 48

Project: lettuce Source File: geometries.py
    @property
    def wkb(self):
        "Returns the WKB representation of the Geometry."
        if sys.byteorder == 'little':
            byteorder = 1 # wkbNDR (from ogr_core.h)
        else:
            byteorder = 0 # wkbXDR
        sz = self.wkb_size
        # Creating the unsigned character buffer, and passing it in by reference.
        buf = (c_ubyte * sz)()
        wkb = capi.to_wkb(self.ptr, byteorder, byref(buf))
        # Returning a buffer of the string at the pointer.
        return buffer(string_at(buf, sz))

Example 49

Project: spectral Source File: envi.py
def _prepared_data_and_metadata(hdr_file, image, **kwargs):
    '''
    Return data array and metadata dict representing `image`.
    '''
    import os
    import sys
    import spectral
    from spectral.io.spyfile import SpyFile, interleave_transpose

    endian_out = str(kwargs.get('byteorder', sys.byteorder)).lower()
    if endian_out in ('0', 'little'):
        endian_out = 'little'
    elif endian_out in ('1', 'big'):
        endian_out = 'big'
    else:
        raise ValueError('Invalid byte order: "%s".' % endian_out)

    if isinstance(image, np.ndarray):
        data = image
        src_interleave = 'bip'
        if len(data.shape) == 2:
            data = data[:, :, np.newaxis]
        swap = False
    elif isinstance(image, SpyFile):
        if image.using_memmap is True:
            data = image._memmap
            src_interleave = {spectral.BSQ: 'bsq', spectral.BIL: 'bil',
                              spectral.BIP: 'bip'}[image.interleave]
            swap = image.swap
        else:
            data = image.load(dtype=image.dtype, scale=False)
            src_interleave = 'bip'
            swap = False
    else:
        data = image.load()
        src_interleave = 'bip'
        swap = False

    metadata = kwargs.get('metadata', {}).copy()
    add_image_info_to_metadata(image, metadata)
    if hasattr(image, 'bands'):
        add_band_info_to_metadata(image.bands, metadata)

    dtype = np.dtype(kwargs.get('dtype', data.dtype)).char
    _validate_dtype(dtype)
    if dtype != data.dtype.char:
        data = data.astype(dtype)
    metadata['data type'] = dtype_to_envi[dtype]

    interleave = kwargs.get('interleave', 'bip').lower()
    if interleave not in ['bil', 'bip', 'bsq']:
        raise ValueError('Invalid interleave: %s'
                         % str(kwargs['interleave']))
    if interleave != src_interleave:
        data = data.transpose(interleave_transpose(src_interleave, interleave))
    metadata['interleave'] = interleave
    metadata['byte order'] = 1 if endian_out == 'big' else 0
    if (endian_out == sys.byteorder and not data.dtype.isnative) or \
      (endian_out != sys.byteorder and data.dtype.isnative):
        data = data.byteswap()

    return data, metadata

Example 50

Project: robothon Source File: functions.py
Function: info
def info(obj, output=sys.stdout, numpy=0):
    if numpy:
        bp = lambda x: x
    else:
        bp = lambda x: int(x)
    cls = getattr(obj, '__class__', type(obj))
    if numpy:
        nm = getattr(cls, '__name__', cls)
    else:
        nm = cls
    print >> output, "class: ", nm
    print >> output, "shape: ", obj.shape
    strides = obj.strides
    print >> output, "strides: ", strides
    if not numpy:
        print >> output, "byteoffset: 0"
        if len(strides) > 0:
            bs = obj.strides[0]
        else:
            bs = obj.itemsize
        print >> output, "bytestride: ", bs
    print >> output, "itemsize: ", obj.itemsize
    print >> output, "aligned: ", bp(obj.flags.aligned)
    print >> output, "contiguous: ", bp(obj.flags.contiguous)
    if numpy:
        print >> output, "fortran: ", obj.flags.fortran
    if not numpy:
        print >> output, "buffer: ", repr(obj.data)
    if not numpy:
        extra = " (DEBUG ONLY)"
        tic = "'"
    else:
        extra = ""
        tic = ""
    print >> output, "data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra)
    print >> output, "byteorder: ",
    endian = obj.dtype.byteorder
    if endian in ['|','=']:
        print >> output, "%s%s%s" % (tic, sys.byteorder, tic)
        byteswap = False
    elif endian == '>':
        print >> output, "%sbig%s" % (tic, tic)
        byteswap = sys.byteorder != "big"
    else:
        print >> output, "%slittle%s" % (tic, tic)
        byteswap = sys.byteorder != "little"
    print >> output, "byteswap: ", bp(byteswap)
    if not numpy:
        print >> output, "type: ", typefrom(obj).name
    else:
        print >> output, "type: %s" % obj.dtype
See More Examples - Go to Next Page
Page 1 Selected Page 2