Android Question Problem with GetBit SetBit

HARRY

Active Member
Licensed User
Longtime User
Hi,

I need to copy the bits of a byte (not the value) to an integer. The reason is that the byte received from elsewhere in fact is an unsigned byte. Based on the sample code I found I tried to do it as follows:

Code: Copy
For i = 0 To 7
    bitresult=GetBit(Light,i)
    Log(Light)
    Log(bitresult)
    intlight=SetBit(intlight,i,bitresult)
Next

and :

Code: Copy
Sub SetBit(b As Int, index As Int, on As Boolean) As Int
    If on Then
        Return Bit.Or(b, Bit.ShiftLeft(1, index))
    Else
        Return Bit.And(b, Bit.Not(Bit.ShiftLeft(1, index)))
    End If
End Sub

Sub GetBit(b As Byte, index As Int) As Boolean
    Dim t As Byte = Bit.ShiftLeft(1, index)
    Return Bit.And(b, t) = t
End Sub

However, it doesn't work; the value of intlight always remains 0x0.

What am I doing wrong?

Harry

Harry
 
Your code works ok. If for instance I set light = -13 (0xF3 as a signed byte) i get intLight=243 (0x000000F3 as a 32-bit int)

However, you can get the same result with just this line
Code: Copy
intlight = Bit.And(light, 0xFF)

for instance, if light=-13 again, it will be implicitly casted to int 0xFFFFFFF3, and the mask will return again 0xF3 as an int, so 243
 
Upvote 0
Back
Top