简体   繁体   中英

Convert 2 integers to hex/byte array?

I'm using a Python to transmit two integers (range 0...4095) via SPI. The package seems to expect a byte array in form of [0xff,0xff,0xff] . So eg 1638(hex:666) and 1229(hex:4cd) should yield [0x66,0x64,0xcd] . So would an effective conversion look like as the mixed byte in the middle seems quite nasty?

You can do it by left shifting and then bitwise OR'ing the two 12-bit values together and using the int_to_bytes() function shown below, which will work in Python 2.x.

In Python 3, the int type has a built-in method called to_bytes() that will do this and more, so in that version you wouldn't need to supply your own.

def int_to_bytes(n, minlen=0):
    """ Convert integer to bytearray with optional minimum length. 
    """
    if n > 0:
        arr = []
        while n:
            n, rem = n >> 8, n & 0xff
            arr.append(rem)
        b = bytearray(reversed(arr))
    elif n == 0:
        b = bytearray(b'\x00')
    else:
        raise ValueError('Only non-negative values supported')

    if minlen > 0 and len(b) < minlen: # zero padding needed?
        b = (minlen-len(b)) * '\x00' + b
    return b

a, b = 1638, 1229  # two 12 bit values
v = a << 12 | b  # shift first 12 bits then OR with second
ba = int_to_bytes(v, 3)  # convert to array of bytes
print('[{}]'.format(', '.join(hex(b) for b in ba)))  # -> [0x66, 0x64, 0xcd]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM