Convert Byte to binary in Java

59,445

Solution 1

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);

Solution 2

For converting hexidecimal into binary, you can use BigInteger to simplify your code.

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;

Solution 3

Alternative to @LINEMAN78s solution is:

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();
}
Share:
59,445
user1506919
Author by

user1506919

Updated on November 18, 2020

Comments

  • user1506919
    user1506919 over 3 years

    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:

    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.

  • jtahlborn
    jtahlborn almost 12 years
    i think the OP is also confused how the hex string "ACDE48" maps to an array of bytes.
  • Maarten Bodewes
    Maarten Bodewes almost 12 years
    You should at least specify how the order of the bits in the string relate to the order of the bits in the byte array, especially as your order seems non-standard. You can actually write fromBinary() without if statements which should speed up your code a bit. StringBuilder can be made ready for the correct size by supplying the size in the constructor (bytes.length * Byte.SIZE). Finally, your fromBinary does accept invalid strings, e.g. digit of value '2' is translated into a zero valued bit.
  • LINEMAN78
    LINEMAN78 almost 12 years
    I am confused as to why you believe that the bit order is non-standard. It is MSB first, however due to the fact that bytes are signed you will have issues with decimal representation if the MSB is set. I also added almost everything you mentioned.
  • Maarten Bodewes
    Maarten Bodewes almost 12 years
    It's MSB for each byte, with the lowest index first. So you would have the lowest order byte first, with the highest order bit first. This is fine, but I would document such things carefully (but I'm a PITA regarding such details). Nice of you to make the changes!
  • LINEMAN78
    LINEMAN78 almost 12 years
    I don't see where endianness comes in here. The bytes are never combined, therefore I am unclear on where you are getting that the lowest order bit is first.
  • Maarten Bodewes
    Maarten Bodewes almost 12 years
    You can still order the bytes from left to right or from right to left, can't you?
  • LINEMAN78
    LINEMAN78 almost 12 years
    The functions output them in the same order they were received. The order of bytes only matters when converting to integers, which is called endianness, which is supported in java.nio.ByteBuffer. The only place in my post where you would need to worry about this is if you use Integer.parseInt and allow it to parse the whole string instead of 2 and 8 characters for hex and binary strings respectively.