gpt4 book ai didi

java - java字节到int的转换,反之亦然

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:08 24 4
gpt4 key购买 nike

我正在尝试将整数转换为字节并在代码中检索该整数。

代码:

ByteArrayOutputStream barrayStream = null;
DataOutputStream outputStream = null;
try {
initSequence();
barrayStream = new ByteArrayOutputStream();
outputStream = new DataOutputStream(barrayStream);
outputStream.writeByte(4);
outputStream.writeInt(xxxx);
System.out.println(" String = "
+ Arrays.toString(barrayStream.toByteArray()));
handlePacket(barrayStream.toByteArray());
}catch (IOException ie) {


ie.printStackTrace();
} finally {
try {
if (barrayStream != null) {
barrayStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}

void handlePacket(byte[] byteArray) throws IOException {

byte[] portArray = new byte[4];
System.arraycopy(byteArray, 1, portArray, 0, 4);
int byteToIntValue = 0;
for (int i = 0; i < portArray.length; i++) {
byteToIntValue = (byteToIntValue << 8) | portArray[i];
}

System.out.println("Port Number = " + byteToIntValue);
}

大于 5120 的整数在检索时给出正确的值。但低于 5119 给出负值这有什么具体原因吗?任何帮助将不胜感激。

输出:对于整数 5100,输出为[0, 0, 19, -20]

对于大于 5120 的整数 [0, 0, 20, 0]

最佳答案

试试这个:

字节到整数:

Byte b = new Byte(rno[0]);
int i = b.intValue();

整数到字节:

int i = 234;
byte b = (byte) i;

在 Java 中字节总是有符号的。不过,您可以通过将其与 0xFF 进行二进制运算来获取其无符号值:

关于java - java字节到int的转换,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20371509/

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