[英]Java ByteBuffer issues with signed and unsigned types converting byte array to integer
我期待這個:
ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == 222
但是以下情況屬實:
ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == -570425344
我如何解決Java在簽名/未簽名類型中的許多限制,或者我是否需要完全自己滾動?
碼:
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);
}
安慰:
BIG_ENDIAN
true
LITTLE_ENDIAN
true
附錄:作為參考,“新創建的字節緩沖區的順序始終為BIG_ENDIAN
。” - ByteBuffer#order()
您觀察到的結果對於小端機器是正確的。 我懷疑如果你運行以下內容,你會得到LITTLE_ENDIAN
作為答案。
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
System.out.println(bb.order());
如果要強制緩沖區使用big-endian排序,請執行以下操作:
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( ));
應打印出來:
BIG_ENDIAN
222
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.