user3020233
user3020233

Reputation: 327

Read binary file byte by byte

I have this weird assignment in my C++ class where I must write a certain number in a binary file (132.147), using the float type, and then read it, using the char type, in such a way that the final result would be the decimal value of each byte (-94, 37, 4 and 67).

fstream binFile("blah.bin", ios::binary|ios::in|ios::out);
float a = 132.147;
binFile.write((char*)&a, sizeof(float));
char b[4];
binFile.read((char*)&b, sizeof(b));
cout << (int)b[0] << ' ' << (int)b[1] << ' ' << (int)b[2] << ' ' << (int)b[3] << endl; // -51 -51 -51 -51
cout << b[0] << ' ' << b[1] << ' ' << b[2] << ' ' << b[3]; // = = = =
binFile.close();
return 0;

I understand where they got those 4 numbers from. If I write the file and read it using an hex editor, I get 4 hexadecimal numbers that, once converted to a signed binary can then be converted to their decimal form. However, I have absolutely no clue how I can programatically do this in C++. Any clue?

Thanks !

Upvotes: 1

Views: 1831

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106068

As Adam says you must reopen the file. You might have noticed it wasn't reading if you'd checked the return value from read. You only need to read sizoef a bytes, but asking to read more is harmless. After you read b...

cout << (int)b[0] << ' ' << ...

Upvotes: 1

Related Questions