将Short转换为3字节数组

时间:2014-07-30 13:02:19

标签: java arrays udp byte

我需要通过UDP传输号码。 协议指定数字为3个字节。

例如,我需要将ID: 258转换为字节数组:

byte[] a = new byte[3]

2 个答案:

答案 0 :(得分:3)

我认为它应该有效:

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

}

答案 1 :(得分:1)

您可以使用DataInputStream:

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

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


byte[] bytes = bout.toByteArray();

如果您必须稍后发送其他数据(例如字符串或其他内容),则可以简单地附加此新数据:

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