how to change some bits in an byte result
Hi All, How to change some bits, with a mask in an byte result from the i2c. readfrom_mem() ?
Trying a lot of solution but all finish by an error!
Is someone can explain how to do it ?
Thanks for help
bytes is immutable you must first convert it to mutable type like
a=bytes([1,2,3]) #create bytes in your case steep not needed you have it already as result from readfrom_mem b=bytearray(a) #convert it to bytearray b=11 #change value to what you need a=bytes(b) #change it back to bytes if you need to
Hi @robert-hh, Already try your first 2 lines with value without success ! already an error " TypeError: 'bytes' object does not support item assignment"
You have to take value, to get an integer. Like
value &= ~(0b00000111 << 4) value |= (mode << 4)
and to get it back into a bytes value:
result = bytes([value & (~(0b00000111 << 4))])
(These many brackets look like LISP, arrgh!!!)
Hi @livius, Ok, thanks but I know that. The problem is when the result of the i2c.readfrom_mem() is for example b'\x34'
value = i2c.readfrom_mem(device addr, register addr, 1) the result is b'\x34'
value &= ~(0b00000111 << 4)
value &| (mode << 4)
I always obtain an error !
below common operators
& | << >>
for changing bit to 1 do
value | (1<<bit_number)
to 0 do:
value & ~(1<<bit_number)
v=4 v5=v | 1 v6=v | (1<<1) print(v5) print(v6)
result should be v5=5 v6=6