B4J Question Set bit in unsigned byte array

ElliotHC

Active Member
Licensed User
Call me old fashioned, but I like my bytes to go from 0-255 because you can't send negative numbers out of the serial port unless they are strings, which kind of defeats the point.

I need to set bits in an unsigned byte array and I'm struggling a bit. Could someone please show an example of how this is done?

I've got two loops, the first counts through the byte array, the second inside that one counts through the bits to set.

I've tried using a combination of these but keep coming up with values I'm not expecting.



B4X:
Sub Unisigned(b As Byte) As Int
 Return Bit.And(0xFF, b)
End Sub

Sub SetBit(b As Byte, index As Int, on As Boolean) As Byte
    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

I think this is because even though I'm using the Unsigned function first, it's still then treating it in the SetBit function as signed.

Thanks
 

stevel05

Expert
Licensed User
Setting and unsetting each bit individually returns the expected results. What are you doing that is returning unexpected results?

B4X:
For i = 0 To 7
        Dim Val As Byte = 0
        Val = SetBit(Val,i,True)
        Log(Unisigned(Val))
        Val = SetBit(Val,i,False)
        Log(Unisigned(Val))
Next

Result
B4X:
1
0
2
0
4
0
8
0
16
0
32
0
64
0
128
0
 
Upvote 0

stevel05

Expert
Licensed User
It worked, or it didn't work? If not what is the value of Bit_count? What result are you expecting?
 
Last edited:
Upvote 0
Top