Problem reading Binary data from file

Oct 28, 2011 at 5:16am
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.
Oct 28, 2011 at 5:36am
 
std::cout <<(int)b
Otherwise, the operator<<(std::ostream &,char) overload will kick in and it will be printed as a character, like in
 
std::cout <<'C'
But:
 
std::cout <<(int)'C'


PS: I wouldn't read a file one byte at a time. As a rule of thumb, try to read at least 4096 bytes (or the entire file, whichever is smaller) at a time from any device.
Last edited on Oct 28, 2011 at 5:38am
Oct 28, 2011 at 5:42am
Helios,

OMG, thank you. That was it. I realize now that the uint8 type is actually just a typecast of an unsigned char (since there's no short short or anything for an 8-bit integer). That's why they print out as characters, not integers. Thank you so much for the sharp eye!
Topic archived. No new replies allowed.