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
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
-
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 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 @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
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
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login