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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Although a reinterpret_cast<unsigned char*>(data) works and is, as far as I know, portable using static_cast<unsigned char*>(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.
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.