Note that there are some explanatory texts on larger screens.

plurals
  1. POJava read binary file (unsigned long long)
    text
    copied!<p>I want to convert a C code to Java. It reads a binary file:</p> <pre><code>int main(int argc, char**argv) { FILE *fd; unsigned long trameNumber = 0; unsigned long long INDEX; fd = fopen(argv[1],"rb"); if (fd == NULL) { printf("Usage %s [File]\n", argv[0]); exit(1); } fread(&amp;INDEX, sizeof(INDEX),1, fd); printf("INDEX %llx\n",INDEX); trameNumber++; while (fread(&amp;INDEX, sizeof(INDEX),1, fd) != 0) { printf("INDEX %llx\n",INDEX); trameNumber++; } fclose(fd); printf("%lu", trameNumber); return 0; } </code></pre> <p>The output with this code looks like:</p> <pre><code>INDEX 0 INDEX 9800000000000000 INDEX 1801000000000000 INDEX 5001000000000000 INDEX b801000000000000 </code></pre> <p>Here is my Java code. I've tried to do that with <code>BigInteger</code>:</p> <pre><code>public static final int DATA_BYTE_LENGHT = 8; public void readBinary(final String readFilePath) { // A 8 byte buffer = 64 bits ByteBuffer byteBuffer = ByteBuffer.allocate(DATA_BYTE_LENGHT); // Those channels will be used to read/write files FileChannel channelFileInput = null; BigInteger bigIndex = null; try { // File to read final File fileRead = new File(readFilePath); // Channel used to read the file. channelFileInput = new FileInputStream(fileRead).getChannel(); byteBuffer.put(new byte[DATA_BYTE_LENGHT]); byteBuffer.rewind(); // While the file has content while( channelFileInput.read(byteBuffer) != -1 ) { byteBuffer.rewind(); // Big integer positive bigIndex = new BigInteger(1, byteBuffer.array()); byteBuffer.rewind(); System.out.println("INDEX "+bigIndex.toString(16)); // Clear the buffer byteBuffer.put(new byte[DATA_BYTE_LENGHT]); byteBuffer.rewind(); } } catch(FileNotFoundException e) { System.err.println("The file cannot be read: "+e.getMessage()); } catch(Exception e) { System.err.println(e.getMessage()); } finally { // Close file connections IOUtils.closeQuietly(channelFileInput); } } </code></pre> <p>However, <code>read()</code> doesn't seem to read the file correctly. Because the output is:</p> <pre><code>INDEX 0 INDEX 98 INDEX 118 INDEX 150 INDEX 1b8 </code></pre> <p>Could it be an endianess problem? How to solve it?</p> <p>Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload