Michael Papageorge
Michael Papageorge

Reputation: 67

Convert bytes to hex value

I have this 32bit value b'F6F3F6F2' arriving in the serial port from an MCU and would like get the two 16bit values that are in there, F6F3 and F6F2 so that I can feed them to the im.putpixel function.

s = serialPort.readline()
s = s.split(b'\n')
print(s[0])  # prints b'F6F3F6F2'
#...
im.putpixel((x,y),((F6F3&0xF800) >> 8, (F6F3&0x07E0) >> 3, (F6F3&0x001F) <<3)) 
im.putpixel((x,y),((F6F2&0xF800) >> 8, (F6F2&0x07E0) >> 3, (F6F2&0x001F) <<3)) 

I can't change the way the MCU sends this data so I have to do this on the python side which I am not that familiar with.

thanks

Upvotes: 0

Views: 173

Answers (2)

Rahul
Rahul

Reputation: 71

byte_value = b'F6F3F6F2'
high, low = byte_value[0:4], byte_value[4:]
print(high, low)

# Convert high, low into int
high_int = int(high, 16)
low_int = int(low, 16)

print(high_int)
print(low_int)

# now you can use those values like
im.putpixel((x,y),((high_int&0xF800) >> 8, (high_int&0x07E0) >> 3, (high_int&0x001F) <<3)) 
im.putpixel((x,y),((low_int&0xF800) >> 8, (low_int&0x07E0) >> 3, (low_int&0x001F) <<3))

Upvotes: 1

David Codery
David Codery

Reputation: 1

from colormap import rgb2hex
from colormap import hex2rgb

print(rgb2hex(255, 255, 255))
print(hex2rgb('#FFFFFF'))

>>> #FFFFFF
>>> (255, 255, 255)

Upvotes: 0

Related Questions