ElliotHC Active Member Licensed User Dec 4, 2020 #1 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: Copy 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
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: Copy 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 Longtime User Dec 4, 2020 #2 Setting and unsetting each bit individually returns the expected results. What are you doing that is returning unexpected results? B4X: Copy 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: Copy 1 0 2 0 4 0 8 0 16 0 32 0 64 0 128 0 Upvote 0
Setting and unsetting each bit individually returns the expected results. What are you doing that is returning unexpected results? B4X: Copy 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: Copy 1 0 2 0 4 0 8 0 16 0 32 0 64 0 128 0
ElliotHC Active Member Licensed User Dec 4, 2020 #3 This worked for me B4X: Copy Dim f as int f = SetBit(Bit.And(0xFF,f), Bit_Count, True) Upvote 0
stevel05 Expert Licensed User Longtime User Dec 4, 2020 #4 It worked, or it didn't work? If not what is the value of Bit_count? What result are you expecting? Last edited: Dec 5, 2020 Upvote 0