Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Numbers as Binary in files

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?!

like image 373
Mohamad Ibrahim Avatar asked May 19 '26 11:05

Mohamad Ibrahim


2 Answers

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

like image 149
stacker Avatar answered May 22 '26 00:05

stacker


What about this ? 0 => 0000 1 => 0001 2 => 0010 3 => 0011 4 => 0100 5 => 0101 6 => 0110 7 => 0111 8 => 1000 9 => 1001

like image 21
nidhin Avatar answered May 22 '26 00:05

nidhin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!