問題描述
我正在嘗試將字節值轉換為二進制以進行數據傳輸.基本上,我在字節數組中以二進制形式(10101100")發送一個像AC"這樣的值,其中10101100"是一個字節.我希望能夠接收這個字節并將其轉換回10101100".到目前為止,我根本沒有成功,真的不知道從哪里開始.任何幫助都會很棒.
I am trying to convert a byte value to binary for data transfer. Basically, I am sending a value like "AC" in binary ("10101100") in a byte array where "10101100" is a single byte. I want to be able to receive this byte and convert it back into "10101100." As of now I have no success at all dont really know where to begin. Any help would be great.
編輯:抱歉,我沒有意識到我忘了添加具體細節.
edit: sorry for all the confusion I didnt realize that I forgot to add specific details.
基本上我需要使用字節數組通過套接字連接發送二進制值.我可以這樣做,但我不知道如何轉換這些值并使它們正確顯示.這是一個例子:
Basically I need to use a byte array to send binary values over a socket connection. I can do that but I dont know how to convert the values and make them appear correctly. Here is an example:
我需要發送十六進制值 ACDE48 并能夠將其解釋回來.根據文檔,我必須通過以下方式將其轉換為二進制:byte [] b={10101100,11011110,01001000},其中數組中的每個位置都可以保存 2 個值.然后,我需要在發送和接收這些值后將它們轉換回來.我不知道該怎么做.
I need to send the hex values ACDE48 and be able to interpret it back. According to documentation, I must convert it to binary in the following way: byte [] b={10101100,11011110,01001000}, where each place in the array can hold 2 values. I then need to convert these values back after they are sent and received. I am not sure how to go about doing this.
推薦答案
String toBinary( byte[] bytes )
{
StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for( int i = 0; i < Byte.SIZE * bytes.length; i++ )
sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
}
byte[] fromBinary( String s )
{
int sLen = s.length();
byte[] toReturn = new byte[(sLen + Byte.SIZE - 1) / Byte.SIZE];
char c;
for( int i = 0; i < sLen; i++ )
if( (c = s.charAt(i)) == '1' )
toReturn[i / Byte.SIZE] = (byte) (toReturn[i / Byte.SIZE] | (0x80 >>> (i % Byte.SIZE)));
else if ( c != '0' )
throw new IllegalArgumentException();
return toReturn;
}
也有一些更簡單的方法來處理這個問題(假設大端).
There are some simpler ways to handle this also (assumes big endian).
Integer.parseInt(hex, 16);
Integer.parseInt(binary, 2);
和
Integer.toHexString(byte).subString((Integer.SIZE - Byte.SIZE) / 4);
Integer.toBinaryString(byte).substring(Integer.SIZE - Byte.SIZE);
這篇關于在Java中將字節轉換為二進制的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!