Byte Array conversion question.

mitsusdev

Member
Licensed User
Longtime User
Hi boys,
i'm newbie on B4A and you did a great job!!

Now, i've a question about byte array conversion and manipulation.
I read from bluetooth an Byte array of 60 bytes. So i want:

1. Change it (Byte Array) from Big Endian to Little Endian
2. Calculate integer value on 2 bytes, 4 bytes, ecc

I've seen many examples, but i'm not able to find a solution for my problem.

Thanks a lot

Francesco
 

mitsusdev

Member
Licensed User
Longtime User
Have a look at the ByteConverter library.

Best regards.

Hi Klaus,i've read about ByteConverter library. Below my test:

B4X:
BConv.LittleEndian = True
BConv.ArrayCopy(Buffer, 0, header, 0,59) 
BConv.ArrayCopy(header,2,subHeader,0,4)
tmpInt = BConv.IntsFromBytes(subHeader) 
   
BConv.ArrayCopy(header,6,subHeaderDev,0,2)
tmpInt2 = BConv.IntsFromBytes(subHeaderDev)

strTmp = BConv.HexFromBytes(subHeaderDev)

I've a buffer (from bluetooth) of 74 bytes. The first 60 bytes are the header and the remaining 14 byes are the data.

I've divided global buffer into wo byte array using a Little Indiann rappresentation.
Now into tmpInt variable (an array of int) i want put 4 bytes from header and convert its into an integer of 4 bytes.

Using the code above, i see "tmpInt" with value 14 (correct!), but...tmpInt2 is not defined and strTmp have value (in Hex) 4101 insted of 1041.

Where are my errors?

Thanks a lot
 
Upvote 0

mitsusdev

Member
Licensed User
Longtime User

Thanks a lot Erel,
I try and update you tonight.
 
Upvote 0

mitsusdev

Member
Licensed User
Longtime User

Dear Erel,
i've follow your advice. Now my question is that if i have a 2 byte array (Es. dc 07 in its hex conversion). I've tried to convert it into an ionteger using IntsFromBytes, but the output is wrong.
On my documentation i see that all integer fields are little-endian.

I've tried to use LittleEndian = True ...then I should see a new reversed string (07 dc)...but the result remains the same (dc 07).

Below the code:

B4X:
BConv.ArrayCopy(header,9,arr_measure_data,0,2) 'Measure Year
BConv.LittleEndian = True
measure_data = BConv.HexFromBytes(arr_measure_data) 'I see DC07 insted of 07DC
Year = BConv.IntsFromBytes(arr_measure_data) ' should be 2012

Thanks a lot
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Here is a solution with RandomAccessFile:
B4X:
Sub Process_Globals
   Dim raf As RandomAccessFile
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
      File.Copy(File.DirAssets, "1.txt", File.DirInternal, "1.txt")
      raf.Initialize2(File.DirInternal, "1.txt", False, True)
   End If
   Log(raf.ReadShort(9)) 'prints 2012
End Sub
 
Upvote 0

mitsusdev

Member
Licensed User
Longtime User

Dear Erel,
thank you for you help. I've solved follw your advise..so i store temporary data into a file and then i use raf.ReadBytes() for read a group of bytes.

Thanks a lot
 
Upvote 0