1

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 !

1
  • 1
    you're almost there. You closed the file, so you must re-open it to read it again. You also want to read 4 bytes, not 10 (sizeof(b)==10 because you made it 10 elements). Note that when you write a float, use sizeof(float) not sizeof(int) Commented Nov 22, 2013 at 4:02

1 Answer 1

1

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] << ' ' << ...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your replies, Adam and Tony. I've edited the piece of code in my initial question with your suggestions. I actually ran it this time and thrown in the outputs. I still don't get it -- both in terms of coding and understanding what's actually going on. What are supposed to represent the first 4 characters I'm reading here? Thanks !
I'm so dumb. I got it now. Thanks a bunch !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.