简体   繁体   English

在Java中将字节转换为二进制

[英]Convert Byte to binary in Java

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. 基本上,我在字节数组中以二进制(“10101100”)发送类似“AC”的值,其中“10101100”是单字节。 I want to be able to receive this byte and convert it back into "10101100." 我希望能够接收此字节并将其转换回“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: 这是一个例子:

I need to send the hex values ACDE48 and be able to interpret it back. 我需要发送十六进制值ACDE48并能够将其解释回来。 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. 根据文档,我必须通过以下方式将其转换为二进制:byte [] b = {10101100,11011110,01001000},其中数组中的每个位置可以包含2个值。 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);

and

Integer.toHexString(byte).subString((Integer.SIZE - Byte.SIZE) / 4);
Integer.toBinaryString(byte).substring(Integer.SIZE - Byte.SIZE);

For converting hexidecimal into binary, you can use BigInteger to simplify your code. 要将十六进制转换为二进制,可以使用BigInteger来简化代码。

public static void sendHex(OutputStream out, String hexString) throws IOException {
    byte[] bytes = new BigInteger("0" + hexString, 16).toByteArray();
    out.write(bytes, 1, bytes.length-1);
}

public static String readHex(InputStream in, int byteCount) throws IOException {
    byte[] bytes = new byte[byteCount+1];
    bytes[0] = 1;
    new DataInputStream(in).readFully(bytes, 1, byteCount);
    return new BigInteger(0, bytes).toString().substring(1);
}

Bytes are sent as binary without translation. 字节以二进制形式发送而不进行转换。 It fact its the only type which doesn't require some form of encoding. 事实上它是唯一不需要某种形式编码的类型。 As such there is nothing to do. 因此,无所事事。

To write a byte in binary 用二进制写一个字节

OutputStream out = ...
out.write(byteValue);

InputStream in = ...
int n = in.read();
if (n >= 0) {
   byte byteValue = (byte) n;

Alternative to @LINEMAN78s solution is: @ LINEMAN78s解决方案的替代方案是:

public byte[] getByteByString(String byteString){
    return new BigInteger(byteString, 2).toByteArray();
}

public String getStringByByte(byte[] bytes){
    StringBuilder ret  = new StringBuilder();
    if(bytes != null){
        for (byte b : bytes) {
            ret.append(Integer.toBinaryString(b & 255 | 256).substring(1));
        }
    }
    return ret.toString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM