I want to save space when writing my data to file. That is I want to store my int numbers as half byte (4bits) only for each digit. I can’t write numbers as characters as that will cost one byte for each digit (the corresponding ASCII code)
I am using the following code to get rid of the first half of the byte and write only 4 bits:
String key= "1234567890"
char[] chars = key.toCharArray();
System.out.println(key+";");
dos.writeLong(l);
for ( int i = 0 ; i < chars.length ; i+= 2 ) {
byte b1 = (byte) (chars[i] - (byte) '0');
byte b2 = (byte) (i < chars.length-1 ? chars[i+1] - (byte) '0': 0xf);
fos.write((byte) ((b1 << 4) | b2 ));
and this code to read back:
String encoded = stt.nextToken( );
StringBuffer result = new StringBuffer();
byte[] buf = encoded.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
for ( int i = 0 ; i < 11 ; i++ ) {
byte both = (byte) bais.read();
byte b1 = (byte) ((both >> 4 ) & 0xf);
byte b2 = (byte) (both & 0xf) ;
result.append( Character.forDigit(b1, 10));
if ( b2 != 0xf ) {
result.append(Character.forDigit(b2,10));
}
}
It’s not working. How could I improve this?
Having done a bit of data stream compression myself, I would suggest another approach: open a ZIP output stream, and write your full data in it. The compression algorithm will take charge of eliminating useless bits (including those you didn’t identify). As a bonus, your code will be easier to read.