简体   繁体   English

将 8 位值转换为 24 位值

[英]Converting 8bit values into 24bit values

I am reading in ADC values, assuming I am reading things right I'm still new to this, from a [NAU7802](14www.nuvoton.com/resource-files/NAU7802 Data Sheet V1.7.pdf0) and I am getting values outputted as an 8 bit integer (ie 0-255) as three bytes.我正在读取 ADC 值,假设我正在阅读正确的内容,我仍然是新手,来自 [NAU7802](14www.nuvoton.com/resource-files/NAU7802 数据表 V1.7.pdf0),我得到了值作为 8 位 integer(即 0-255)作为三个字节输出。 How do I merge the three bytes together to get the output as a 24bit value (0-16777215)?如何将三个字节合并在一起以将 output 作为 24 位值 (0-16777215)?

Here is the code I am using, if I am assuming I did this right, I am still new to I2C communication.这是我正在使用的代码,如果我假设我做对了,我还是 I2C 通信的新手。

from smbus2 import SMBus
import time

bus = SMBus(1)
address = 0x2a
bus.write_byte_data(0x2a, 0x00, 6)
data = bus.read_i2c_block_data(0x2a,0x12,3)
print bus.read_i2c_block_data(0x2a,0x12,3)
adc1 = bin(data[2])
adc2 = bin(data[1])
adc3 = bin(data[0])
print adc1
print adc2
print adc3

When I convert the binary manually I get and output that corresponds to what I am inputting to the adc.当我手动转换二进制文件时,我得到和 output 对应于我输入到 adc 的内容。 Ouput:输出:

[128, 136, 136]
0b10001001
0b10001000
0b10000000

try this:尝试这个:

data=[128, 136, 136]                                                                                                                                                                              
data[0] + (data[1] << 8) + (data[2] << 16) 
# 8947840

or或者

((data[2] << 24) | (data[1] << 16) | (data[0] << 8)) >> 8
# 8947840
(8947840 & 0xFF0000) >> 16                                                                                                                                                                          
#136

(8947840 & 0x00FF00) >> 8
#136

(8947840 & 0x0000FF) 
#128

Here's an example on unpacking 3 different numbers:这是一个拆包 3 个不同数字的示例:

data=[118, 123, 41]                                                                                                                                                                              

c = data[0] + (data[1] << 8) + (data[2] << 16)                                                                                                                                                        
#2718582

(c & 0xFF0000) >> 16                                                                                                                                                                          
#41

(c & 0x00FF00) >> 8                                                                                                                                                                         
#123

(c & 0x0000FF)
#118

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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