0

I need to transfer numbers over UDP. The protocol specifies the numbers to be 3 bytes.

So for example I need ID: 258 converted to a byte array:

byte[] a = new byte[3]
Hackerman
  • 12,139
  • 2
  • 34
  • 45
Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66

2 Answers2

3

I think it should work:

Little Endian:

byte[] convertTo3ByteArray(short s){

   byte[] ret = new byte[3];
   ret[2] = (byte)(s & 0xff);
   ret[1] = (byte)((s >> 8) & 0xff);
   ret[0] = (byte)(0x00);

   return ret;

}

short convertToShort(byte[] arr){

    if(arr.length<2){
        throw new IllegalArgumentException("The length of the byte array is less than 2!");
    }

    return (short) ((arr[arr.length-1] & 0xff) + ((arr[arr.length-2] & 0xff ) << 8));       
}

Big Endian:

byte[] convertTo3ByteArray(short s){

   byte[] ret = new byte[3];
   ret[0] = (byte)(s & 0xff);
   ret[1] = (byte)((s >> 8) & 0xff);
   ret[2] = (byte)(0x00);

   return ret;

}

short convertToShort(byte[] arr){

    if(arr.length<2){
        throw new IllegalArgumentException("The length of the byte array is less than 2!");
    }

    return (short) ((arr[0] & 0xff) + ((arr[1] & 0xff ) << 8));

}
Zangdak
  • 242
  • 4
  • 22
1

You could use a DataInputStream:

ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutput out = new DataOutputStream();

out.write(0); //to have 3 bytes
out.writeShort(123);


byte[] bytes = bout.toByteArray();

If you have to send other data to a later time (e.g. string or something) you then can simple append this new data:

ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutput out = new DataOutputStream();

out.write(0); //to have 3 bytes
out.writeShort(123);


out.writeUTF("Hallo UDP");

byte[] bytes = bout.toByteArray();
morpheus05
  • 4,772
  • 2
  • 32
  • 47