Segfault > IT > Programming > Java: how to read an unsigned int

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:


  1. public static void main(String[] args) {
  2. File fInFile;
  3. FileInputStream fisInFile;
  4. BufferedInputStream bisInFile;
  5. DataInputStream disInFile;
  6. ...
  7. long lFilesize;
  8. try {
  9. fInFile = new File("/home/shared/programming/java/openFile/liftmeup.wav");
  10. fisInFile = new FileInputStream(fInFile);
  11. bisInFile = new BufferedInputStream(fisInFile);
  12. disInFile = new DataInputStream(bisInFile);
  13. ...
  14. lFilesize = readBytesLittle2Big(disInFile, 4);
  15. System.out.print("Remaining file length: "); System.out.println(lFilesize);
  16. ...
  17. }
  18. }
  19.  
  20. public static long readBytesLittle2Big(DataInputStream d, int iHowmany) throws IOException {
  21. byte[] b = new byte[iHowmany];
  22. ByteBuffer bb = ByteBuffer.allocate(iHowmany);
  23. for (int x=0;x<iHowmany;x++)
  24. {
  25. b[x] = d.readByte();
  26. }
  27. /*Here I read stuff from disc which is saved in little endian order which I have to convert into big endian*/
  28. for (int x=0;x<iHowmany;x++)
  29. {
  30. bb.put(iHowmany-1-x, b[x]);
  31. }
  32. bb.rewind();
  33. return bb.getInt();
  34. }

Again: I don't know if this is 100% correct (how does the int get assigned to the long when the fuction returns? Is there an implicit conversion?), but it seems to work... .

(Btw, iIn the meanwhile I had some other complications with Java, and went back to my old, flexible, segmentation-crashy C/C++ :o) )