gpt4 book ai didi

java - 从java中的字节数组中获取无符号整数

转载 作者:行者123 更新时间:2023-11-30 06:13:31 25 4
gpt4 key购买 nike

我需要从字节数组中获取无符号整数。我知道 java 不支持无符号原语,我必须使用更高的原语(long)来获得无符号整数。许多人通常建议解决方案如下:

public static long getUnsignedInt(byte[] data)
{
ByteBuffer bb = ByteBuffer.wrap(data);
bb.order(ByteOrder.LITTLE_ENDIAN);
return bb.getInt() & 0xffffffffl;
}

但这并不聪明,因为我们必须得到有符号整数然后将其转换为无符号整数,这当然可能导致溢出异常。我看到其他解决方案使用 BigInteger 或新的 Java 8 未签名功能,但我无法让它做我想做的事。

最佳答案

But this is not smart since we have to get signed integer then convert it to unsigned which of course may result in overflow exception.

没有所谓的“溢出异常”。您的解决方案将始终准确有效地工作。别担心了。

关于java - 从java中的字节数组中获取无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750160/

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