Combine 4 bytes into one in Java -
here 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 bits of each byte zero, except rightmost 2 bits, can 0 or 1. changed code 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 getting expected (01110010):
xxd -b x.bin 0000000: 01010000 p
why?
you mistake hex literals
binary literals
:
0x11; // hex 11, dec 17, bits 00010001 0b11; // hex 3, dec 3, bits 00000011
Comments
Post a Comment