-1

我正在python3.4使用venv.

我正在为传感器编写脚本,在读取配置文件后,我需要将一个发送int到串行端口bytearray

类函数的片段是:

def set_sampling(self, type, sampling_us):
        conf_buffer = bytearray([0xfe, 0x06])
        if type not in self.sensor_ids:
            print('Sensor not identified')
        else:
            conf_buffer.append(self.sensor_ids[type])
            conf_buffer.append(0x02)
            if (sampling_us > 0):
                print(sampling_us)
                sampling_bytes = (sampling_us).to_bytes(4, 'little')
                conf_buffer += sampling_bytes
            self.send_frame(conf_buffer)
            self.enable(type)

框架结构应该是小端0xf6 0x06 sensor_id 0x02 sampling_us格式sampling_us

我目前sampling_us有 1000000(等于 1 秒)

当我在解释器中执行以下操作时:

>>> (1000000).to_bytes(4, 'little')

提供的结果是:

>>> b'@B\x0f\x00'

但是我用传感器的脚本进行了交叉检查,其中 1000000 的字节实际上是b'\x40\x42\x0f\x00'

我通过执行以下操作撤销了检查:

 >>> int.from_bytes(b'\x40\x42\x0f\x00', 'little')
 >>> 1000000

正确的字节实际上b'\x40\x42\x0f\x00'是因为如果发送给它的字节数组是传感器不响应b'@B\x0f\x00'

为什么我在这里得到一个差异?我在这里做错了什么?

4

1 回答 1

3

如果你这样做

>>> b'\x40\x42\x0f\x00' == b'@B\x0f\x00'
True

您会看到没有差异,您只是在查看同一字节串的两种不同表示。在b'...'表示法上,Python 的默认表示是任何可打印的 ascii 字符都显示为该字符而不是\x转义符。

于 2019-05-22T09:57:36.927 回答