Android Question IntsToBytes pads integers to 4 bytes, how can I strip the zeros efficiently?

jimseng

Active Member
Licensed User
Longtime User
Hello. I am learning about sending UDP packets and byteconverter. Since an integer is 4 bytes, when converting 2 ints to bytes I end up with an 8 byte array, so at the moment I am stripping the padded zeros manually before sending them, in order to only send 2 bytes. This is because I am obsessing about efficiency and if I were doing this with BLE I would only have a 20 byte payload (I think?).
The following works but it seems a very manual process. I wonder if there is a better way to do it?
I have tried converting the int to a string and using GetBytes("UTF8") but this seems madness and requires a char conversion at the receiving end.

B4X:
private Sub udp(ch As Int,v As Int)
    
    Dim Packet As UDPPacket
    Dim bc As ByteConverter
    Dim intarray() As Int = Array As Int(ch,v)
    Dim data() As Byte = bc.IntsToBytes(intarray)
    Log(data.As (List)) 'reuslt: (ArrayList) [0, 0, 0, 1, 0, 0, 0, 30]
    Dim sp(2) As Byte
    sp(0) = data(3)
    sp(1) = data(7)
    Packet.Initialize(sp,B4XPages.MainPage.ip, B4XPages.MainPage.port)
    UDPServer.Send(Packet)
    
End Sub
 
Top