2013-11-09 27 views
1

我有一个20字节的字节[]。
我需要读取前4个字节并将它们转换为单个无符号整数,然后再转换为字符串。
该字节生成一个大整数,所以当我转换为一个整数,然后在一个字符串中,我有一个负数。
例如:0x53,0x2D,0x78,0xAA。 我转换他们:从字节转换为大的无符号整数和字符串

 hash = bHash[0]|bHash[1]<<8|bHash[2]<<16|bHash[3]<<24; 
     keyid = String.valueOf(hash); 
     keyid = Integer.toString(hash); 

和我在这两种情况下:“-1434964653”,但我需要生成“2860002643”。

+0

Java没有无符号整数这里 –

+0

看:http://stackoverflow.com/a/3353020/1739882和http://stackoverflow.com/a/10803658/1739882 –

回答

1

由于在Java中没有unsigned int类型,使用长型:

long hash = (bHash[0]|bHash[1]<<8|bHash[2]<<16|bHash[3]<<24)&0xFFFFFFFFl; 
String keyid = String.valueOf(hash); 
keyid = Long.toString(hash); 
0

我写了一个小例子。

这是我用来操纵字节的库。

@Test 
public void readUnsignedInt() { 
    //0x53, 0x2D, 0x78, 0xAA. 
    //http://stackoverflow.com/questions/19874527/conversion-from-bytes-to-large-unsigned-integer-and-string 
    ByteBuf buf = ByteBuf.create (20); 
    buf.addByte (0xAA); 
    buf.addByte (0x78); 
    buf.addByte (0x2D); 
    buf.addByte (0x53); 

    byte[] bytes = buf.readForRecycle(); 

ByteBuf是一个轻量级的可重用缓冲区。 Boon是一个用于在Java和其他实用程序中实现切片符号的库。

您可以使用idxUnsignedInt读取无符号字节,第二个参数是偏移量。

long val = idxUnsignedInt (bytes, 0); 

    boolean ok = true; 

BTW死引发运行时异常并返回一个布尔值,以便你能短路或它表达式来创建一个断言类型不能由编译器被关断的。 :)

ok |= val == 2860002643L || die(); //die if not equal to 2860002643L 

你也可以阅读多头(你没有问,但我想告诉你无论如何)。

buf.add (2860002643L); 

    bytes = buf.readForRecycle(); 

    val = idxLong (bytes, 0); 

    ok |= val == 2860002643L || die(); 

您还可以将无符号整数添加到字节数组缓冲区。适合测试。

//add unsigned int to the byte buffer. 
    buf.addUnsignedInt (2860002643L); 

    //read the byte array of the buffer 
    bytes = buf.readForRecycle(); 

    //Read the unsigned int from the array, 2nd arg is offset 
    val = idxUnsignedInt (bytes, 0); 

    //Convert it to string and print it to console 
    puts("" + val); 

    ok |= val == 2860002643L || die(); 

以上内容涵盖了您的问题的所有部分。它读取并将其转换为字符串。

这是再次转换为字符串。

ok |= ("" + val).equals("2860002643") || die(); 

现在只是几个更多的组合。

//Read the unsigned int from the array, 2nd arg is offset 
    byte [] bytes2 = new byte[] { 
      (byte)0xAA, 0x78, 0x2D, 0x53, 0, 
        0,  0, 0, 0, 0, 
        0,  0, 0, 0, 0, 
        0 ,  0, 0, 0, 0 }; 


    val = idxUnsignedInt (bytes2, 0); 

    ok |= val == 2860002643L || die(); 


    //Deal direct with bytes 
    byte [] bytes3 = new byte[20]; 


    unsignedIntTo (bytes3, 0, 2860002643L); 

    val = idxUnsignedInt (bytes2, 0); 

    ok |= val == 2860002643L || die(); 

} 

我永远不会记得如何做到这一点,我厌倦了查找它,所以我写了这些东西。

您可以在这里阅读关于ByteBuf的更多信息。 :)

https://github.com/RichardHightower/boon/wiki/Auto-Growable-Byte-Buffer-like-a-ByteBuilder

相关问题