qed
qed

Reputation: 23114

Combine 4 bytes into one in Java

Here is the code:

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

public class Shiftcodes {
    private Map<byte[], Byte> shiftMap;

    public byte genoByte(byte b1, byte b2, byte b3, byte b4) {
        return (byte) (
                  (b1 << 6)
                | (b2 << 4)
                | (b3 << 2)
                | b4);
    }

    public static void main(String[] args) throws IOException {
        Shiftcodes shiftcodes = new Shiftcodes();
        byte b = shiftcodes.genoByte((byte) 0x01, (byte) 0x11, (byte) 0x00, (byte) 0x10);
        FileOutputStream fileOutputStream = new FileOutputStream("/tmp/x.bin");
        fileOutputStream.write(new byte[] {b});
    }
}

It's assumed that the bits of each byte are all zero, except the rightmost two bits, which can be 0 or 1. So I changed the code a little:

public class Shiftcodes {
    private Map<byte[], Byte> shiftMap;

    public byte genoByte(byte b1, byte b2, byte b3, byte b4) {
        return (byte) (
                  ((b1 & 0x11) << 6)
                | ((b2 & 0x11) << 4)
                | ((b3 & 0x11) << 2)
                | b4);
    }

    public static void main(String[] args) throws IOException {
        Shiftcodes shiftcodes = new Shiftcodes();
        byte b = shiftcodes.genoByte((byte) 0x01, (byte) 0x11, (byte) 0x00, (byte) 0x10);
        FileOutputStream fileOutputStream = new FileOutputStream("/tmp/x.bin");
        fileOutputStream.write(new byte[] {b});
    }
}

But in both cases I am getting what I expected (01110010):

xxd -b x.bin
0000000: 01010000                                               P

Why?

Upvotes: 1

Views: 184

Answers (2)

folkol
folkol

Reputation: 4883

You mistake hex literals for binary literals:

0x11; // Hex 11, Dec 17, Bits 00010001
0b11; // Hex 3,  Dec 3,  Bits 00000011

Upvotes: 5

John Kugelman
John Kugelman

Reputation: 361710

The rightmost two bits would be 0x3 not 0x11. 0x11 is 00010001 in binary rather than 00000011.

return (byte) (
          ((b1 & 0x3) << 6)
        | ((b2 & 0x3) << 4)
        | ((b3 & 0x3) << 2)
        | b4);

Upvotes: 6

Related Questions