I have numbers written as ASCII codes in my file. For example "9" is stored as two bytes 57 i.e. 8 bits in total.
I want to optimize storage by just storing those numbers as binary values for example numbers from 0-9 to be stored using 4 bits only.
Any help?!
You could write them binary like that
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Bin {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("\\test.bin");
String digits="12345";
char[] chars = digits.toCharArray();
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 ));
}
fos.close();
FileInputStream fis = new FileInputStream("\\test.bin");
StringBuffer result = new StringBuffer();
byte[] buf = new byte[100];
int read = fis.read(buf);
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
for ( int i = 0 ; i < read ; 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));
}
}
System.out.println(result.toString());
}
}
But I doubt that this will be very useful
What about this ? 0 => 0000 1 => 0001 2 => 0010 3 => 0011 4 => 0100 5 => 0101 6 => 0110 7 => 0111 8 => 1000 9 => 1001
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With