I come from a C/C++ background and I just started using Java.
Why Java? Well, I thought it would be nice to be able to use my programs as well on other operating systems and machines without the need to modify and recompile the code.

The first big problem I faced was what to do when I want to work with unsigned variables, more explicitly how to put unsigned values I read from binary files into Java-variables, as Java apparently doesn't support unsigned data types.

The solution I found was to read from disk the informations byte-by-byte, put them into an array of bytes, convert them and put the result into the destination variable, which has to be bigger than the original value (because of the sign).

Nasty stuff! So, here is how I do it, but honestly after reviewing it I am not very sure that this works, but still hope that this will "inspire" you to get the right way of doing it:


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.nio.ByteBuffer;
import java.io.File;
import java.io.IOException;

public class thisisatest {

public static void main(String[] args) {
        File fInFile;
        FileInputStream fisInFile;
        BufferedInputStream bisInFile;
        DataInputStream disInFile;

        long lFilesize;
        try {
                fInFile = new File("/home/shared/programming/java/openFile/liftmeup.wav");
                fisInFile = new FileInputStream(fInFile);
                bisInFile = new BufferedInputStream(fisInFile);
                disInFile = new DataInputStream(bisInFile);

                lFilesize = readBytesLittle2Big(disInFile, 4);
                System.out.print("Remaining file length: "); System.out.println(lFilesize);
        }
        catch(Exception e) {

                System.out.print("Something went wrong.");
        }
}
 
public static long readBytesLittle2Big(DataInputStream d, int iHowmany) throws IOException {
        byte[] b = new byte[iHowmany];
        ByteBuffer bb = ByteBuffer.allocate(iHowmany);
        for (int x=0;x<iHowmany;x++)
        {
                b[x] = d.readByte();
        }
        /*Here I read stuff from disc which is saved in little endian order which I have to convert into big endian*/
        for (int x=0;x<iHowmany;x++)
        {
                bb.put(iHowmany-1-x, b[x]);
        }
        bb.rewind();
        return bb.getInt();
}

}

Save that code in a file called "thisisatest.java" and compile it with "javac thisisatest.java".