Java 将 32 位无符号整数(大端)转换为 long 和 back

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9855087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 12:22:09  来源:igfitidea点击:

Converting 32-bit unsigned integer (big endian) to long and back

javatype-conversionendiannessunsigned-integer

提问by Aviram

I have a byte[4] which contains a 32-bit unsigned integer (in big endian order) and I need to convert it to long (as int can't hold an unsigned number).

我有一个 byte[4],它包含一个 32 位无符号整数(按大端顺序),我需要将其转换为 long(因为 int 不能保存无符号数)。

Also, how do I do it vice-versa (i.e. from long that contains a 32-bit unsigned integer to byte[4])?

另外,反之亦然,我该怎么做(即从包含 32 位无符号整数的 long 到 byte[4])?

采纳答案by Edwin Dalorzo

Sounds like a work for the ByteBuffer.

听起来像是ByteBuffer的作品。

Somewhat like

有点像

public static void main(String[] args) {
    byte[] payload = toArray(-1991249);
    int number = fromArray(payload);
    System.out.println(number);
}

public static  int fromArray(byte[] payload){
    ByteBuffer buffer = ByteBuffer.wrap(payload);
    buffer.order(ByteOrder.BIG_ENDIAN);
    return buffer.getInt();
}

public static byte[] toArray(int value){
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.order(ByteOrder.BIG_ENDIAN);
    buffer.putInt(value);
    buffer.flip();
    return buffer.array();
}

回答by Hot Licks

You can use ByteBuffer, or you can do it the old-fashioned way:

您可以使用 ByteBuffer,也可以使用老式的方法:

long result = 0x00FF & byteData[0];
result <<= 8;
result += 0x00FF & byteData[1];
result <<= 8;
result += 0x00FF & byteData[2];
result <<= 8;
result += 0x00FF & byteData[3];