在Java中将4个字节合并为一个

qed*_*qed 1 java

这是代码:

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});
    }
}
Run Code Online (Sandbox Code Playgroud)

假设每个字节的位都是零,除了最右边的两位,可以是0或1.所以我改变了一点代码:

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});
    }
}
Run Code Online (Sandbox Code Playgroud)

但在这两种情况下我都得到了我的预期(01110010):

xxd -b x.bin
0000000: 01010000                                               P
Run Code Online (Sandbox Code Playgroud)

为什么?

Joh*_*ica 6

最右边的两位0x3不是0x11.0x11是二进制而不是00000011的00010001.

return (byte) (
          ((b1 & 0x3) << 6)
        | ((b2 & 0x3) << 4)
        | ((b3 & 0x3) << 2)
        | b4);
Run Code Online (Sandbox Code Playgroud)


fol*_*kol 5

你错hex literalsbinary literals:

0x11; // Hex 11, Dec 17, Bits 00010001
0b11; // Hex 3,  Dec 3,  Bits 00000011
Run Code Online (Sandbox Code Playgroud)