【问题标题】:Converting 32-bit unsigned integer (big endian) to long and back将 32 位无符号整数(大端)转换为 long 并返回
【发布时间】:2012-04-08 22:49:12
【问题描述】:

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

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

【问题讨论】:

  • 字节数组从何而来?

标签: java type-conversion endianness unsigned-integer


【解决方案1】:

听起来像是 ByteBuffer 的作品。

有点像

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

【讨论】:

  • 如果我错了,请纠正我,但如果我这样做int value = buffer.getInt();,那么 int 可能无法包含整个数字(如果它是未签名且未签名的)。
  • @Aviram Java 中的一个整数是 32 位(4 个字节),只要你的 ByteBuffer 是 4 个字节长,我不明白为什么会有问题。我已经改进了我的答案,并用正面和负面的方式对其进行了测试,到目前为止它工作得很好。我可能会遗漏一些东西吗?如果您打算使用无符号整数,请使用 long 而不是整数,因为 Java 中的整数是有符号的。
  • 您可以使用return buffer.getInt() & 0xFFFFFFFFL;,因为您将始终获得无符号值。 ByteBuffer 默认为 BIG_ENDIAN。您无需致电flip() 即可使用array()
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    【讨论】:

    • 好点,仅使用 Peter Lawrey 在此问题的一个评论中描述的 & 0xFFFFFFFFL 方法是过分的。
    • 为什么 toLong(Integer.MIN_VALUE) 不起作用?并返回负长 ideone.com/cERLo1
    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2016-11-30
    • 2019-05-30
    • 1970-01-01
    • 2012-10-19
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多