将字节数组块转换为DWORD(int)Java

时间:2017-01-31 13:40:51

标签: java decimal block endianness

如何将4字节数组块转换为整数。

如果我们在Hex Editor中有这些字节的文件:

CB 01 00 00

此块的十六进制值为十进制000001CB = 1CB十六进制= 459的DWORD。

如何将任何字节数组(byte[])块(四个字节)转换为整数(块的十进制值)?

我正在寻找这样的方法:

public int getDecimalFromBlock( byte... bytes ) {
      for ( byte b: bytes ) {
          // do the magic
      }
}

其中参数字节的数字在字节范围(-127,127)之间。

2 个答案:

答案 0 :(得分:3)

我们假设您的字节顺序是Little Endian(基于您的帖子),因此解码将是

int value = ((data[0]&0xff) |
    ((data[1]&0xff)<<8) |
    ((data[2]&0xff)<<16) |
    ((data[3]&0xff)<<24));

如果订单是Big endian,它将类​​似于:

int value = ((data[3]&0xff) |
    ((data[2]&0xff)<<8) |
    ((data[1]&0xff)<<16) |
    ((data[0]&0xff)<<24));

在这两种情况下,变体&#34;数据&#34;是&#34; byte []&#34;

byte[] data = new byte[] {(byte)0xcb, 0x01, 0x00, 0x00};

更新已修改的请求。

我假设您可能将0xcb的问题解释为负值,这可以通过应用&运算符来修复

包含测试用例的完整代码

public class DecimalTest
{
    public static int getDecimalFromBlock( byte... bytes ) {
        int result = 0;
        for(int i=0; i<bytes.length; i++)
        {
            result = result | (bytes[i] & 0xff)<<(i*8);
        }
        return result;
    }

    public static void main(String[] args) throws IOException
    {
        System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb}));
        System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb, 0x01}));
        System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb, 0x01, 0x00}));
        System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb, 0x01, 0x00, 0x00}));
        System.out.println(getDecimalFromBlock(new byte[]{(byte)0xcb, 0x01, 0x00, 0x00, 0x00}));
    }
}

答案 1 :(得分:0)

您还可以查看Apache Commons IO库及其EndianUtils类。这正是出于这个目的。

请注意,四字节DWORD(无符号)只能正确映射到Java(带符号)long,因为Java(带符号)int无法保存DWORD的所有可能值(太大的值会导致负int值)。因此EndianUtils.readSwappedUnsignedInteger()正确返回long

相关问题