0

I have a file with data like:

1F B8 08 08 00 00 00 00

I am reading it into an int, casting it to a character, and storing it in an array.

int n, i = 0;
char c;
while (ifs >> std::hex >> n) {
   c = static_cast<unsigned char>(n);
   r[i++] = c;
}

works fine. How do I go about doing this if there is no white space in the data, i.e.

1FB8080800000000

The above code just fills n to maxint and exits. I can create something using getc or the like but I'd like the C++ code to handle both cases.

1 Answers1

1

You could read the numbers as strings and use std::setw to limit the number of characters read. Then use std::stoi to convert to integers:

std::string ns;
while (ifs >> std::setw(2) >> ns) {
    r[i++] = static_cast<unsigned char>(std::stoi(ns, nullptr, 16));
}

Will work with both the space-delimited and non space-delimited input.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I'm trying to use `code` while (ifs >> std::setw(2) >> std::hex >> i) `code` where i is an integer. Returns 0x7FFFFFFF. I'd like to avoid all the string/casting rigamarole. Why would that code not return a hex char? – Mark Jackson Dec 06 '20 at 20:28