B4J Question unsigned bytes

sorex

Expert
Licensed User
Longtime User
Hello,

Can anyone explain me why I always get a negative "byte" (which doesn't seem to be a byte but a double word) once I store an 8 bit value with bit 7 set?

why is it setting all the other 24 bits aswell?

the code below outputs

byte >ffffff80 >-128
int >80 >128
-128
-128
128

so it seems that a negative 7 bit value, which is just a positive 8 bit value unsigned, is always stored as 32 bit negative value so I must always mask out all the other bits? even the storing of the correct int value gets messed up.


B4X:
Dim bytes(2) As Byte
Dim byteval As Byte
Dim intval As Int

byteval=Bit.Or(byteval,Power(2,7 ) )
'byteval=Bit.And(byteval,0xff)  < this doesn't help either
Log("byte >"&Bit.ToHexString(byteval) &" >"& byteval)

intval=Bit.Or(intval,Power(2,7 ) )
Log("int >"&Bit.ToHexString(intval) &" >"& intval)

bytes(0)=byteval:Log(bytes(0))
bytes(0)=intval:Log(bytes(0))
Log(Bit.And(bytes(0),0xff))
 

sorex

Expert
Licensed User
Longtime User
I'm filling a byte array with 8 bit based values that will be saved to disk.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Don't convert the byte to int as it will add more confusion.

B4X:
Sub AppStart (Form1 As Form, Args() As String)
   Dim b As Byte
   b = SetBit(b, 7, False)
   b = SetBit(b, 6, True)
   b = SetBit(b, 5, True)
   b = SetBit(b, 4, True)
   Dim bc As ByteConverter
   Log(bc.HexFromBytes(Array As Byte(b)))
End Sub

Sub SetBit(b As Byte, index As Int, value As Boolean) As Byte
   If value Then
     Return Bit.Or(b, Bit.ShiftLeft(1, index))
   Else
     Return Bit.And(b, Bit.Not(Bit.ShiftLeft(1, index)))
   End If
End Sub
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
in the end all went fine. I just got confused by these FFFFFFxx values and thought it might write out 4 bytes instead of just 1.
 
Upvote 0
Top