Convert 2 integers to hex/byte array?

萝らか妹 提交于 2019-12-12 05:29:09

问题


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 e.g. 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?


回答1:


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]


来源:https://stackoverflow.com/questions/44803084/convert-2-integers-to-hex-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!