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];*)&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]; // = = = =
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 !


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] << ' ' << ...

Need Your Help

HTML5 FS API: Let the user create files outside of the sandbox?

javascript filesystems

Is there a way to create a file outside of the sandbox? Maybe something that works by first storing the file inside the sandbox and then letting the user drag a link to the locally stored file into a

Why is the perspective argument in a pb.Viewable passed as None?

python twisted perspective-broker

I am trying to understand how to find out how to allow a server to know which client is making remote requests in twisted's perspective broker. I think I'm supposed to use twisted.spread.pb.Viewabl...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.