-2

I read a huge binary file into a vector of chars.

I need to treat every byte as an unsigned integer(from 0 to 255); and do some arithmetics. How can I convert vector to vector?


char a = 227;
cout << a;

prints ?


char a = 227;
int b = (int) a;
cout << b << endl;

prints -29


char a = 227;
unsigned int b = (unsigned int) a;
cout << b << endl;

prints 4294967267


char a = 227;
unsigned char b = (unsigned char) a;
cout << b << endl;

prints ?

mustafa
  • 3,605
  • 7
  • 34
  • 56
  • I already have that vector. when I convert `char` to `unsigned char` it still prints ? – mustafa Nov 30 '15 at 20:51
  • char -> unsigned char -> int/unsigned – Kevin Nov 30 '15 at 20:52
  • @Kevin yes it does the trick. Is there an easy way of converting the vector to vector in one step? – mustafa Nov 30 '15 at 20:57
  • You should be able to use the constructor taking 2 iterators (`std::vector uchars(chars.begin(), chars.end());`) If you already constructed the 2nd vector you can use `clear` and `insert`. Printing this will still have the same issue. – Kevin Nov 30 '15 at 20:59
  • What about instead of unsigned int, you make it a byte? Does that give you what you want? A byte has a valid range of 0 to 255. – Russ Nov 30 '15 at 21:37
  • @Russ - byte is not a standard type in C or C++. – Pete Becker Dec 01 '15 at 00:13
  • Seems like you're using the wrong data structure. Using `vector` instead of `vector` will eliminate the signedness issues without having to convert any data. – Pete Becker Dec 01 '15 at 00:19

1 Answers1

0
std::vector<char> source;
// ... read values into source ...

// Make a copy of source with the chars converted to unsigned chars.
std::vector<unsigned char> destination;
for (const auto s : source) {
  destination.push_back(static_cast<unsigned char>(s))
}

// Examine the values in the new vector.  We cast them to int to get
// the output stream to format it as a number rather than a character.
for (const auto d : destination) {
    std::cout << static_cast<int>(d) << std::endl;
}
Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175