简体   繁体   中英

Converting char to unsigned integer

I read a huge binary file into a vector of char s.

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 ?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM