質問

I am trying to write nothing but uint32_t data to a .bin file. I start by opening up a file stream which I declare to be a binary one.

  `hartInStream.open (hartFileToWrite.c_str(), std::ifstream::binary);
   if(!hartOutStream.is_open())
        {
        printf("Something in outstream went wrong.\n");  
        }
   else 
        {
        printf("Yippy! it outstream worked!\n");  
        printf("---------Starting to read-------------\n");}`

Next, I take the data I am trying to write, in this case a uint32_t "data", print it out, and write it to the end of my file stream.

printf(" Reading %lu from HART at %d-%d-%d\n", data, (int)addr1, (int)addr2, (int)addr3 );

Lastly I append the data

hartOutStream<<data;

I know that I should be writing 0x00 0x00 0x01 0x00 (256) as the first 4 bytes but I am writing 32 35 36 which is the hex equivalent of ascii charters to 256. (using HxD file viewer)

I suspect the problem is in the << operator where it typecasts it to ascii. I've tried typecasting, the atoi() function but nothing seems to work. Does anyone know what is wrong with this?

Thanks

役に立ちましたか?

解決

ofstream f;
f.open("my.bin",std::ofstream::binary);
uint32_t data=0x00000100;
f.write((char*)&data,sizeof(data));

他のヒント

The << operators format to text. If you want a binary format, you'll have to format manually into a std::vector<char>, then write that out using std::ostream::write(). Something like:

std::vector<char> buf;
buf.push_back( (data >> 24) & 0xFF );
buf.push_back( (data >> 16) & 0xFF );
buf.push_back( (data >>  8) & 0xFF );
buf.push_back( (data      ) & 0xFF );
hartOutStream.write( buf.data(), buf.size() );

(If you are using an older C++, you might need to write &buf[0], rather than buf.data().)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top