簡體   English   中英

如何將二進制字符串轉換為java中2字節的字節數組

[英]How to convert binary string to the byte array of 2 bytes in java

我有二進制字符串String A = "1000000110101110" 我想在java將此字符串轉換為長度為2的字節數組

我已經接受了這個鏈接的幫助

我試圖通過各種方式將其轉換為字節

  1. 我先將該字符串轉換為十進制,然后將代碼應用於存儲到字節數組中

     int aInt = Integer.parseInt(A, 2); byte[] xByte = new byte[2]; xByte[0] = (byte) ((aInt >> 8) & 0XFF); xByte[1] = (byte) (aInt & 0XFF); System.arraycopy(xByte, 0, record, 0, xByte.length); 

但是存儲到字節數組中的值是負數

xByte[0] :-127
xByte[1] :-82

哪個是錯誤的值。

我也試過用

byte[] xByte = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(aInt).array();

但它會在上面的行中引發異常

  java.nio.Buffer.nextPutIndex(Buffer.java:519)     at
  java.nio.HeapByteBuffer.putInt(HeapByteBuffer.java:366)   at
  org.com.app.convert.generateTemplate(convert.java:266)

我現在該怎么做才能將二進制字符串轉換為2字節的字節數組?在java是否有任何內置函數來獲取字節數組

嘗試這個

String s = "1000000110101110";
int i = Integer.parseInt(s, 2);
byte[] a = {(byte) ( i >> 8), (byte) i};
System.out.println(Arrays.toString(a));
System.out.print(Integer.toBinaryString(0xFF & a[0]) + " " + Integer.toBinaryString(0xFF & a[1]));

產量

[-127, -82]
10000001 10101110

即-127 == 0xb10000001和-82 == 0xb10101110

使用putShort輸入兩個字節的值。 int有四個字節。

// big endian is the default order
byte[] xByte = ByteBuffer.allocate(2).putShort((short)aInt).array();

順便說一句, 你的第一次嘗試是完美的 由於設置了這些字節的最高有效位,因此無法更改字節的負號。 這總是被解釋為負值。

10000001 2 == -127

10101110 2 == -82

字節符號為8位整數。 因此,您的結果是完全正確的。 即:01111111是127,但10000000是-128。 如果你想獲得0-255范圍內的數字,你需要使用更大的變量類型,如short。

您可以將字節打印為無符號,如下所示:

public static String toString(byte b) {
    return String.valueOf(((short)b) & 0xFF);
}

你得到的答案

 xByte[0] :-127
 xByte[1] :-82

是對的。

這被稱為2的贊美Represantation。 第1位用作有符號位。

0 for +ve
1 for -ve

如果第1位為0,則計算為常規位。 但如果第1位為1,則從128中扣除7位的值,並以-ve形式呈現答案。

在你的情況下,第一個值是10000001所以1(第1位)-ve和128-1(最后7位)= 127所以值是-127

有關詳細信息,請參閱2的補碼表示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM