gpt4 book ai didi

Java 整数转字节数组转短整型

转载 作者:行者123 更新时间:2023-11-30 05:27:17 25 4
gpt4 key购买 nike

我正在尝试将整数转换为字节数组(4 个字节的数组),然后提取每个字节的最后 4 位,然后从每个字节的最后 4 位数字创建一个短值。

我有以下代码,但它总是打印零。


private static short extractShort(byte[] byteArray) {
short s = 1;
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
for(int i = 0; i < byteArray.length; i++) {
byte lastFourBytes = extractLast4Bits(byteArray[i]);
// Uses a bit mask to extract the bits we are interested in
byteBuffer.put(lastFourBytes);
}
return ByteBuffer.wrap(byteBuffer.array()).getShort();
}


private static byte extractLast4Bits(byte byteParam) {
return (byte) ( byteParam & 0b00001111);
}

private static byte[] intToByteArray(int i) {
return new byte[] {
(byte)((i >> 24) & 0xff),
(byte)((i >> 16) & 0xff),
(byte)((i >> 8) & 0xff),
(byte)((i >> 0) & 0xff),
};
}

}

任何帮助将不胜感激

最佳答案

获得字节数组后,试试这个..


short val = 0;
for (byte b : bytes) {
val <<= 4;
val |= (b&0xf)
}

如果你想从int开始,你可以这样做。

      int v = 0b1110_1010_1111_1001_1010_1000_1010_0111;
short verify = (short) 0b1010_1001_1000_0111;
// initialize a short value
short val = 0;

// increment from 24 to 0 by 8's the loop will
// repeat 4 times.
for (int i = 24; i >= 0; i -= 8) {
// start by shifting the result left 4 bits
// first time thru this does nothing.
val <<= 4;

// Shift the integer right by i bits (first time is
// 24, next time is 16, etc
// then mask off the lower order 4 bits of the right
// most byte and OR it to the result(val).
// then when the loop continues, val will be
// shifted left 4 bits to allow for the next "nibble"

val |= ((v >> i) & 0xf);
}
System.out.println(val);
System.out.println(verify);

有关按位运算符的更多信息,请查看此 Wikipedia链接。

关于Java 整数转字节数组转短整型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58273335/

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