Search code examples
javabinarybinaryfiles

Reading integer from bin file does modulu(256) on number which are larger than 256


I'm trying to read numbers from a bin file, when it gets to a number which is larger than 256, it does a modulu(256) on that number, for example: the number which i'm trying to read is 258, the number which was read from the file is (2) => 258mod256=2 how can I read the full number ? This is a snippet from the code:

InputStream ReadBinary = new BufferedInputStream(new FileInputStream("Compressed.bin"));
    int BinaryWord = 0;
    while(BinaryWord != -1) {
        BinaryWord = ReadBinary.read();
        if(BinaryWord != -1)
        System.out.println(BinaryWord + ": " + Integer.toBinaryString(BinaryWord));

Code for writing the file:

        DataOutputStream binFile = new DataOutputStream(new FileOutputStream("C:\\Users\\George Hanna\\eclipse-workspace\\LZW\\Compressed.bin"));
    //convert codewords to binary to send them.
    for(int i=0;i<result.size();i++)
        try {
            IOFile.print(Integer.toBinaryString(result.get(i))+ " ");
            binFile.writeByte(result.get(i));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    binFile.close();

Solution

  • Just to give a little bit of background on how integers are stored:

    To summarize it, your file consists of bytes. Every byte has a value between 0 and 255.

    To represent an 32-bit int, you need 4 bytes.

    Java has int(4 bytes) and long(8 bytes).

    The easiest way to store data in a binary file is with the DataOutputStream, and read it with DataInputStream. It will handle all those conversions for you.

    DataOutputStream out = new DataOutputStream(new FileOutputStream("intFile.bin"));
    out.writeInt(123456789);
    out.close();
    
    DataInputStream in = new DataInputStream(new FileInputStream("intFile.bin"));
    System.out.println(in.readInt());
    in.close();
    

    To get the single bytes from the file, do this:

    InputStream in_bytes = new FileInputStream("intFile.bin");
    int nextByte = in_bytes.read();
    while(nextByte != -1) {
        System.out.println(nextByte);
        nextByte = in_bytes.read();
    }
    in_bytes.close();
    

    To write single bytes to a file, do this:

    OutputStream out_bytes = new FileOutputStream("intFile.bin");
    out_bytes.write(1);
    out_bytes.write(2);
    out_bytes.write(3);
    out_bytes.write(4);
    out_bytes.close();
    

    But as you already realized, what you are writing here are bytes, and therefore you are limited to the range between 0 and 255.