Michael H.
Michael H.

Reputation: 93

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 (i.e. 0-255) as three bytes. How do I merge the three bytes together to get the output as a 24bit value (0-16777215)?

Here is the code I am using, if I am assuming I did this right, I am still new to I2C communication.

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. Ouput:

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

Upvotes: 4

Views: 793

Answers (1)

oppressionslayer
oppressionslayer

Reputation: 7224

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:

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

Upvotes: 3

Related Questions