Search code examples
cfilebufferfopenfread

Reading 2 bytes from a file and converting to an int gives the wrong output


Basically I have a text file that contains a number. I changed the number to 0 to start and then I read 2 bytes from the file (because an int is 2 bytes) and I converted it to an int. I then print the results, however it's printing out weird results.

So when I have 0 it prints out 2608 for some reason.

I'm going off a document that says I need to read through a file where the offset of bytes 0 to 1 represents a number. So this is why I'm reading bytes instead of characters...

I imagine the issue is due to reading bytes instead of reading by characters, so if this is the case can you please explain why it would make a difference?

Here is my code:

void readFile(FILE *file) {
    char buf[2];
    int numRecords;

    fread(buf, 1, 2, file);

    numRecords = buf[0] | buf[1] << 8;

    printf("numRecords = %d\n", numRecords);
}

I'm not really sure what the buf[0] | buf[1] << 8 does, but I got it from another question... So I suppose that could be the issue as well.


Solution

  • The number 0 in your text file will actually be represented as a 1-byte hex number 0x30. 0x30 is loaded to buf[0]. (In the ASCII table, 0 is represented by 0x30)

    You have garbage data in buf[1], in this case the value is 0x0a. (0x0a is \n in the ASCII table)

    Combining those two by buf[0] | buf[1] << 8 results in 0x0a30 which is 2608 in decimal. Note that << is the bit-wise left shift operator.

    (Also, the size of int type is 4-byte in many systems. You should check that out.)