Search code examples
javahexarrayssignedendianness

How to convert raw image into signed 32 bit


I have a file created with dd command (raw file). I opened it with bless as shown in the image below:

Bless

Now I would like to extract the data from this file and get what appears under Signed 32 bit (If you see the image 84 is the number I want). Therefore, I want to convert the following string in this way:

10 00 00 00 --> 84
54 00 00 00 --> 70185301

In order to do this conversion I built the following program which opens the file, decode the line and write the result in a new file.

Here is the piece of code that does the extraction (@Duncan Helped me to create it):

try
  {
 
    File input = new File(inputFileField.getText());
    File output = new File(fileDirectoryFolder.getText() +"/"+ input.getName());

    byte[] buffer = new byte[8];         
    DataOutputStream out = new DataOutputStream(new FileOutputStream(output)); 
    DataInputStream in = new DataInputStream(new FileInputStream(input));

    int count = 0;        
    
    while (count < input.length() - 4) {

        in.readFully(buffer, 4, 4);
        String s= Long.toString(ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getLong());
        out.writeBytes( s+ " ");        
        count += 4;
     }
   }
   System.out.println("Done"); 
     
}
catch(FileNotFoundException e1){}

However, the result I get is

10 00 00 00 --> 68719476736 
54 00 00 00 --> 360777252864

Do you understand where my problem is?

Thanks


Solution

  • String s= 
    Integer.toString(
       ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt());
    

    Long has 8 bytes, you want to convert only 4.

    And don't use an offset

    in.readFully( buffer, 0, 4 );
    
    $ echo $[0x1000000000]
    68719476736
    $ echo $[0x5400000000]
    360777252864
    

    This is due to the (incorrect) offset of 4 bytes when reading.

    And another one, that should be corrected:

     while (count < input.length() - 3) {