Reputation: 1276
I need to read binary data to buffer, but in the fstreams I have read function reading data into char buffer, so my question is:
How to transport/cast binary data into unsigned char buffer and is it best solution in this case?
Example
char data[54];
unsigned char uData[54];
fstream file(someFilename,ios::in | ios::binary);
file.read(data,54);
// There to transport **char** data into **unsigned char** data (?)
// How to?
Upvotes: 2
Views: 761
Reputation: 6546
You don't need to declare the extra array uData. The data array can simply be cast to unsigned:
unsigned char* uData = reinterpret_cast<unsigned char*>(data);
When accessing uData you instruct the compiler to interpret the data different, for example data[3] == -1, means uData[3] == 255
Upvotes: 2
Reputation: 153792
You could just use
std::copy(data, data + n, uData);
where n
is the result returned from file.read(data, 54)
. I think, specifically for char*
and unsigned char*
you can also portably use
std::streamsize n = file.read(reinterpret_cast<char*>(uData));
Upvotes: 1
Reputation: 87944
Just read it into unsigned char data in the first place
unsigned char uData[54];
fstream file(someFilename,ios::in | ios::binary);
file.read((char*)uData, 54);
The cast is necessary but harmless.
Upvotes: 4