为了账号安全,请及时绑定邮箱和手机立即绑定

在Java中将字节数组转换为整数,反之亦然

在Java中将字节数组转换为整数,反之亦然

素胚勾勒不出你 2019-08-12 15:56:57
在Java中将字节数组转换为整数,反之亦然我想将一些数据存储到Java中的字节数组中。基本上只是每个数字最多可以占用2个字节的数字。我想知道如何将整数转换为2字节长字节数组,反之亦然。我发现了很多解决方案谷歌搜索,但大多数都没有解释代码中发生了什么。有很多变化的东西,我真的不明白,所以我很感激一个基本的解释。
查看完整描述

3 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

使用java.nio命名空间中找到的类,特别是ByteBuffer。它可以为您完成所有工作。


byte[] arr = { 0x00, 0x01 };

ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default

short num = wrapped.getShort(); // 1


ByteBuffer dbuf = ByteBuffer.allocate(2);

dbuf.putShort(num);

byte[] bytes = dbuf.array(); // { 0, 1 }


查看完整回答
反对 回复 2019-08-12
?
慕仙森

TA贡献1827条经验 获得超8个赞

byte[] toByteArray(int value) {
     return  ByteBuffer.allocate(4).putInt(value).array();}byte[] toByteArray(int value) {
    return new byte[] { 
        (byte)(value >> 24),
        (byte)(value >> 16),
        (byte)(value >> 8),
        (byte)value };}int fromByteArray(byte[] bytes) {
     return ByteBuffer.wrap(bytes).getInt();}// packing an array of 4 bytes to an int, big endian, minimal parentheses// operator precedence: <<, &, | // when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to rightint fromByteArray(byte[] bytes) {
     return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);}// packing an array of 4 bytes to an int, big endian, clean codeint fromByteArray(byte[] bytes) {
     return ((bytes[0] & 0xFF) << 24) | 
            ((bytes[1] & 0xFF) << 16) | 
            ((bytes[2] & 0xFF) << 8 ) | 
            ((bytes[3] & 0xFF) << 0 );}

将有符号字节打包到int中时,需要屏蔽掉每个字节,因为由于算术提升规则(在JLS,转换和促销中描述),它被符号扩展为32位(而不是零扩展)。

Joshua Bloch和Neal Gafter在Java Puzzlers(“每个字节中的大喜悦”)中描述了一个有趣的谜题。将字节值与int值进行比较时,将字节符号扩展为int,然后将此值与另一个int进行比较

byte[] bytes = (…)if (bytes[0] == 0xFF) {
   // dead code, bytes[0] is in the range [-128,127] and thus never equal to 255}

请注意,所有数字类型都使用Java签名,但char是16位无符号整数类型。


查看完整回答
反对 回复 2019-08-12
?
森林海

TA贡献2011条经验 获得超2个赞

您还可以将BigInteger用于可变长度字节。您可以将其转换为long,int或short,以满足您的需求。

new BigInteger(bytes).intValue();

或表示极性:

new BigInteger(1, bytes).intValue();

要获取字节只是:

new BigInteger(bytes).toByteArray()


查看完整回答
反对 回复 2019-08-12
  • 3 回答
  • 0 关注
  • 1259 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号