2

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?
CppMonster
  • 1,216
  • 4
  • 18
  • 35

3 Answers3

4

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.

john
  • 85,011
  • 4
  • 57
  • 81
2

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

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
Jasper
  • 6,076
  • 2
  • 14
  • 24
  • Although a `reinterpret_cast(data)` works and is, as far as I know, portable using `static_cast(data)` does _not_ work. ... and I think your last statement is not correct in general: for one, `char` may be `unsigned` and I don't think two's complement is strictly required. – Dietmar Kühl Nov 23 '13 at 21:51
1

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));
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380