i have a function defined as follows:
void AddHeadCode(std::ofstream &ostream, size_t length){
ostream.write((char*)length, sizeof(length));
ostream.seekp(0x10L, std::ios::beg);
}
Now when this executes, it will fail obviously... as the char pointer will point nowhere. But i want the actual pointervalue written into the file. Like length = 19152 Then when I open up the file in an HEX Editor, I should find 0d4a there.
How can this be achieved in c++? Im kinda lost here...
Take the address of your length
variable, and pass that address to .write
:
void AddHeadCode(std::ofstream &ostream, size_t length){
// by popular demand, removed C-style cast
ostream.write(reinterpret_cast<char*>(&length), sizeof(length));
ostream.seekp(0x10L, std::ios::beg);
}
But, this is not usually refered to as writing an integer "as hex". This is sometimes referred to as writing an integer "as binary", or simply writing an integer.
Note that what you have done is not a portable practice. If you read the value back in on a different computer (or even on the same computer, but with a different compiler), you might not read in the same value.
Filestreams are tricky so I am uncertain about that but I use this for stringstreams:
std::basic_stringstream<wchar_t> oTmpStream;
oTmpStream << L"0x" << std::nouppercase << std::setfill( L'0' ) << std::hex << std::setw( 8 ) << iSomeValue
// or without fancy formatting;
oTmpStream << std::hex << iSomeValue
reinterpret_cast<char*>(&length)
- ipc 2012-04-05 14:55