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 helpJiemde
-
@jiemde
bytes is immutable you must first convert it to mutable type likebytearray
e.g.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[1]=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[0] without success ! already an error " TypeError: 'bytes' object does not support item assignment"
Jiemde
-
@jiemde said in how to change some bits in an byte result:
You have to take value[0], to get an integer. Like
value[0] &= ~(0b00000111 << 4) value[0] |= (mode << 4)
and to get it back into a bytes value:
result = bytes([value[0] & (~(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'
example:
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 !
-
@jiemde
below common operators& | << >>
for changing bit to 1 do
value | (1<<bit_number)
to 0 do:
value & ~(1<<bit_number)
e.g.v=4 v5=v | 1 v6=v | (1<<1) print(v5) print(v6)
result should be v5=5 v6=6