开发者

Java ByteBuffer issues with signed and unsigned types converting byte array to integer

开发者 https://www.devze.com 2023-03-13 03:17 出处:网络
I expected this: ByteBuffer.wrap(开发者_如何学JAVAnew byte[] { 0, 0, 0, -34 }).getInt() == 222 However the following is true:

I expected this:

ByteBuffer.wrap(开发者_如何学JAVAnew byte[] { 0, 0, 0, -34 }).getInt() == 222

However the following is true:

ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == -570425344

How do I get around this yet another of Java's many limitations with signed/unsigned types or do I need to completely roll my own?


Code:

public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
    System.out.println(bb.order());
    System.out.println(bb.getInt() == 222);
    bb.rewind();
    bb.order(ByteOrder.LITTLE_ENDIAN);
    System.out.println(bb.order());
    System.out.println(bb.getInt() == -570425344);
}

Console:

BIG_ENDIAN
true
LITTLE_ENDIAN
true

Addendum: For reference, "The order of a newly-created byte buffer is always BIG_ENDIAN."—ByteBuffer#order()


The result you observe is correct for a little-endian machine. I suspect if you run the following, you'll get LITTLE_ENDIAN as the answer.

ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
System.out.println(bb.order());

If you want to force big-endian ordering for your buffer, do the following:

ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
bb.order(ByteOrder.BIG_ENDIAN);
System.out.println(bb.order());
System.out.println(bb.getInt( ));

Should print out:

BIG_ENDIAN
222
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号