Hello,
I am having trouble with reading single bytes of data in from a binary file. The data I'm reading is to be interpreted as an integer, so when I read in the data, I do a type cast and store it as an 8-bit integer (see code). However, when I try to print out the data, it is either blank or a weird symbol, like '@' or '?'.
Interestingly, I have no trouble when I try to read in multiple bytes of data. I only get garbage data when I try to read in a single byte. As far as I can tell, the only difference between me reading in multiple bytes and me reading in a single byte is that when I read in a single byte, I don't worry about the byte order, so I don't call ntohs() or ntohl(). Other than that, the process is exactly the same. So why would I be getting bad data?
1 2 3 4 5 6 7 8 9 10 11 12
|
//uint8 is a typedef for an 8-bit int
//uint16 is a typedef of a short int
//buffers to store the data
char singleByte[1];
char twoBytes[2];
ifstream fin(filename);
fin.read(twoBytes, 2);
fin.read(singleByte, 1);
uint16 a = ntohs((uint8) twoBytes[0] + ((uint8) twoBytes[1] << 8));
uint8 b = (uint8) singleByte[0];
|
When I do this code and cout << a, it prints an integer (the correct value I expect from manually reading the binary file in a hex editor). However, when I cout << b, it either doesn't print anything (not even a blank space) or it prints a '@' or '?'.
Any ideas? As always, thanks everyone.