Alexander Ciesielski
Alexander Ciesielski

Reputation: 10834

Convert Short to 3 bytes array

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]

Upvotes: 0

Views: 140

Answers (2)

morpheus05
morpheus05

Reputation: 4872

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();

Upvotes: 1

Zangdak
Zangdak

Reputation: 242

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));

}

Upvotes: 3

Related Questions