byte conversion

Rusty

Well-Known Member
Licensed User
Longtime User
I am receiving tokens via TCP in byte arrays.
The first element within the byte array is a value of i.e. 253. When I receive the byte, it displays as -2 within the array.
Is this a sign bit issue? If this is correct, how do I convert the byte to a value of 253? (i.e. byteconverter.bytestoint(?) or ???)
thanks in advance
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Basic4android type system is based on Java type system. In this type system there is only a signed byte. Which means that a value of a byte is between -128 to 127.

You can use this method to read unsigned byte:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim b As Byte
   b = 253 
   Log(b) 'will print -3
   Log(ConvertSignedByteToUnsigned(b)) '253
End Sub

Sub ConvertSignedByteToUnsigned(b As Byte) As Int
   Return Bit.And(b, 0xFF)
End Sub
 
Upvote 0

hangloose99

Member
Licensed User
Longtime User
Is there a way to write an unsigned byte with Astreams?
e.g. the value "253" bufferTX(0)? --> AStreams.Write(bufferTX)
 
Upvote 0

hangloose99

Member
Licensed User
Longtime User
ok... thank you, than it seems there is a problem with my
CRC calculation. if the value for the CRC is <= 127 everthing works fine.
If the value is > 127 it won't work.
do you have any ideas? :(


Dim k As Int

intCrc16RX = Bit.Xor(intCrc16RX, buf)
For j = 0 To 7 Step 1 ' for each bit
k = Bit.And(intCrc16RX,1) ' memo bit 0 state
intCrc16RX = Bit.And(((Bit.And(intCrc16RX,0xFFFE)) / 2) , 0x7FFF) ' Shift right with 0 at left
If k > 0 Then intCrc16RX = Bit.Xor(intCrc16RX,0xA001) ' Bocuse
Next

Return intCrc16
 
Upvote 0

hangloose99

Member
Licensed User
Longtime User
this is the working code in "C"
Maybe there is a way to translate to B4A
:sign0013: i'm only a :sign0104:

unsigned int crc16_update(unsigned int crc, unsigned char a)
{
unsigned char i;

crc ^= a;
for (i = 0; i < 8; ++i)
{
if (crc & 1)
crc = (crc >> 1) ^ 0xA001;
else
crc = (crc >> 1);
}

return crc;
}
 
Upvote 0
Top