简体   繁体   English

用Java将4个字节合并为1个字节

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

But in both cases I am getting what I expected (01110010): 但是在两种情况下,我都达到了我的期望(01110010):

xxd -b x.bin
0000000: 01010000                                               P

Why? 为什么?

The rightmost two bits would be 0x3 not 0x11 . 最右边的两位将是0x3而不是0x11 0x11 is 00010001 in binary rather than 00000011. 0x11二进制0x11是00010001,而不是00000011。

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

You mistake hex literals for binary literals : 您将hex literals误认为是binary literals

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

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

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