gpt4 book ai didi

java - 将 Short 转换为 3 字节数组

转载 作者:行者123 更新时间:2023-12-01 18:28:56 25 4
gpt4 key购买 nike

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

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

byte[] a = new byte[3]

最佳答案

我认为它应该有效:

小端:

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

大端:

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

}

关于java - 将 Short 转换为 3 字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25037550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com