在Java中将字节转换为二进制
我正在尝试将字节值转换为二进制以进行数据传输.基本上,我在字节数组中以二进制形式(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);
相关文章