我写了一个小例子。
这是我用来操纵字节的库。
@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
Java没有无符号整数这里 –
看:http://stackoverflow.com/a/3353020/1739882和http://stackoverflow.com/a/10803658/1739882 –