从 Java 中的字节数组创建一个 48 位有符号值

我正在尝试从字节数组中提取 6 个字节并将它们转换为 48 位有符号整数值(即 Java 长整数)。如何做到这一点?

编辑:例如,如果字节数组具有以下之一:

byte[] minInt48 = new byte[] { (byte)0x80, 0, 0, 0, 0, 0 };
byte[] maxInt48 = new byte[] { (byte)0x7F, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF };

如何将其解析为 Java 原语(即 Java long)以保留符号值?


繁星coding
浏览 149回答 1
1回答

慕尼黑8549860

首先,您需要了解符号扩展。您需要将每个字节视为无符号值。&nbsp; &nbsp; &nbsp; long v = 0;&nbsp; &nbsp; &nbsp; byte q = -2; // unsigned value of 254&nbsp; &nbsp; &nbsp; v = v + q;&nbsp; &nbsp; &nbsp; System.out.println(v); // prints -2 which is not what you want.&nbsp; &nbsp; &nbsp; v = 0;&nbsp; &nbsp; &nbsp; v = v + (q & 0xFF); // mask off sign extension from q.&nbsp; &nbsp; &nbsp; System.out.println(v); // prints 254 which is correct.这是一种方法。&nbsp; &nbsp; &nbsp;long val = 0;&nbsp; &nbsp; &nbsp;byte[] bytes = { -1, 12, 99, -121, -3, 123&nbsp; &nbsp; &nbsp;};&nbsp; &nbsp; &nbsp;for (int i = 0; i < bytes.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; // shift the val left by 8 bits first.&nbsp; &nbsp; &nbsp; &nbsp; // then add b.&nbsp; You need to mask it with 0xFF to&nbsp; &nbsp; &nbsp; &nbsp; // eliminate sign extension to a long which will&nbsp; &nbsp; &nbsp; &nbsp; // result in an incorrect conversion.&nbsp; &nbsp; &nbsp; &nbsp; val = (val << 8) | ((i == 0 ? bytes[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : bytes[i] & 0xFF));&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;System.out.println(val);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java