Android Question Help: How to convert integer higher than 255 to 2 bytes ?

RushilD

Member
Licensed User
Hello All,

I am building an App that sends data over BLE

I am using the following code

B4X:
    Dim bc As ByteConverter
    Dim setting_ID As Byte

For i = 0 To 999
        
    'setting_ID = bc.IntsToBytes(Array As Int(i))

    'Log(i & " Dec = " & setting_ID & " Hex")

    setting_ID = i

    Log(i & " Dec = " & setting_ID & " Hex")

    Dim DataToSend() As Byte = Array As Byte(0x00,0x00,0x0E,0x00,[B]BYTE_1,BYTE_0[/B],0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)

    manager.WriteData(BLE_SERVICE_UUID,SETTINGS_UUID, DataToSend)


Problem:

When i = 255
255 -> 00FF

(I need to interchange the order while sending)
BYTE_0 = 0xFF
BYTE_1 = 0x00

When i = 256
256 -> 0100

I want the following
BYTE_0 = 01
BYTE_1 = 00

I found a code where I can generate the following

B4X:
For i = 254 To 300
        
        Log(bc.HexFromBytes(bc.IntsToBytes(Array As Int(i))))
        hex = bc.HexFromBytes(bc.IntsToBytes(Array As Int(i)))
        hex = hex.SubString(4)
        Log(hex)

Output
B4X:
00FE
00FF
0100
0101
...


How can I separate the 2 bytes that are strings and convert them into BYTE_0 and BYTE_1

Thank you!
 

teddybear

Well-Known Member
Licensed User
Code block title:
Dim ib(1) as int
ib(0) = 256
Dim b() as byte = bc.intstobytes(ib)
Dim BYTE_0, BYTE_1 as byte
Byte_0 = b(2)
Byte_1 = b(3)
 
Upvote 0

emexes

Expert
Licensed User
B4X:
Dim bc As ByteConverter

For i = 254 To 257    'or 0 to 999 per your code
    Dim b() As Byte = bc.IntsToBytes(Array As Int(i))    'convert Int to 4 Bytes
    Dim Byte_0 As Byte = b(2)    'high byte of 16-bit value (0..65535 aka 0x0000..0xFFFF aka 0..2^16-1)
    Dim Byte_1 As Byte = b(3)    'low byte

    Log(i & TAB & bc.HexFromBytes(Array As Byte(Byte_0)) & TAB & bc.HexFromBytes(Array As Byte(Byte_1)))

    Dim DataToSend() As Byte = Array As Byte(0x00, 0x00, 0x0E, 0x00, Byte_1, Byte_0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)    '18 bytes
Next

Log output:
Waiting for debugger to connect...
Program started.
254    00    FE
255    00    FF
256    01    00
257    01    01
Program terminated (StartMessageLoop was not called).
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
If you're not totally set on using ByteConverter, you can also use Bit methods to accomplish the same thing:
B4X:
Dim Byte_0 As Byte = Bit.And(Bit.ShiftRight(i, 8), 0xFF)
Dim Byte_1 As Byte = Bit.And(i, 0xFF)
 
Upvote 0
Top