简体   繁体   English

将字符转换为无符号整数

[英]Converting char to unsigned integer

I read a huge binary file into a vector of char s.我将一个巨大的二进制文件读入了一个char向量。

I need to treat every byte as an unsigned integer(from 0 to 255);我需要将每个字节视为一个无符号整数(从 0 到 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打印 -29


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

prints 4294967267打印 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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