这是代码:

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


假定每个字节的位都为零,除了最右边的两位(可以为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});
    }
}


但是在两种情况下,我都达到了我的期望(01110010):

xxd -b x.bin
0000000: 01010000                                               P


为什么?

最佳答案

您将hex literals误认为binary literals

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

关于java - 用Java将4个字节合并为1个字节,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30818930/

10-09 05:33