Bit.OR Question

wl

Well-Known Member
Licensed User
Longtime User
Hello,

I'm trying to do some bit operations (esp. OR) on bytes and get some very strange results. I boiled it down to:


B4X:
Dim foo as byte = 0
foo = Bit.OR (foo, Bit.ShiftLeft(1, 7))

Bit.ToBinaryString (foo) 'I would except to get 10000000,but I get 1111111111111111111111110000000 ?

I guess it has something to do with the fact the Bit operators return ints, but still I don't get it ?
 
Last edited:

MLDev

Active Member
Licensed User
Longtime User
foo is a signed byte variable with a range of -128 to 127. 10000000 is -128. The value of foo is passed as an integer value to Bit.ToBinaryString. 11111111111111111111111110000000 is -128.

You can convert foo to an unsigned byte and return it as an integer with this:

B4X:
Bit.And(foo, 0xff)
 
Last edited:
Upvote 0

wl

Well-Known Member
Licensed User
Longtime User
Thanks, that was indeed the point (the fact that all bit operations work on integers and that bytes are unsigned).

I ended up in do all the needed bit operations on ints and at the end convert them to bytes using the Bit.And (anInt, 0xff)

Thanks
 
Upvote 0
Top