Вопрос

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?
Это было полезно?

Решение

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.

Другие советы

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

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));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top