关于位操作:在Python中加入两个十六进制整数

Join two hex integers in Python

我只是Python的新手,目前在Raspberry Pi上使用I2C从数字罗盘读取2个字节。 MSB和LSB值存储在一个数组中,例如
a = [0x07, 0xFF]

我想将这两个字节合并为一个变量,例如
b == 0x07FF

我将如何去做呢?
我认为将MSB乘以256并将其添加到LSB就像将它一样容易,但是我不断收到" IndexError:列表索引超出范围"
任何帮助,将不胜感激:)

我的代码是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import smbus
import time

bus = smbus.SMBus(1)

addr = 0x1E

bus.write_byte_data(addr, 0x00, 0x70)
bus.write_byte_data(addr, 0x01, 0xA0)
bus.write_byte_data(addr, 0x02, 0x00)
time.sleep(0.006)

for i in range(0,10):
    x = bus.read_i2c_block_data(addr,0x03,2)
    y = bus.read_i2c_block_data(addr,0x07,2)
    z = bus.read_i2c_block_data(addr,0x05,2)

    xval = 256*x[2]+x[1]
    print x, y, z
    print xval
    time.sleep(1)
print 'exiting...'

我得到的错误是:

1
2
3
4
Traceback (most recent call last):
  File"compass2.py", line 18, in <module>
    xval = 256*x[2]+x[1]
IndexError: list index out of range


如注释中所述,在Python中,索引始于0,而不是1。在代码中,索引始于x[0],而不是x[1]

合并两个从0到255的整数:

按位使用

信用:这个答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
MAXINT = 255  # Must be a power-of-two minus one
NUM_BITS = MAXINT.bit_length()

def merge(a, b):
    c = (a << NUM_BITS) | b
    return c

def split(c):
    a = (c >> NUM_BITS) & MAXINT
    b = c & MAXINT
    return a, b

# Test:
EXPECTED_MAX_NUM_BITS = NUM_BITS * 2
for a in range(MAXINT + 1):
    for b in range(MAXINT + 1):
        c = merge(a, b)
        assert c.bit_length() <= EXPECTED_MAX_NUM_BITS
        assert (a, b) == split(c)

使用算术

此技术有效,但不是首选。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
MAXINT_PLUS1 = 256

def merge(a, b):
    c = MAXINT_PLUS1 * a + b
    return c

def split(c):
    a, b = divmod(c, MAXINT_PLUS1)
    return a, b

# Test:
EXPECTED_MAX_NUM_BITS = (MAXINT_PLUS1 - 1).bit_length() * 2
for a in range(MAXINT_PLUS1):
    for b in range(MAXINT_PLUS1):
        c = merge(a, b)
        assert c.bit_length() <= EXPECTED_MAX_NUM_BITS
    assert (a, b) == split(c)