正在将char转换为无符号整数

Converting char to unsigned integer

本文关键字:无符号整数 转换 char      更新时间:2023-10-16

我将一个巨大的二进制文件读取到char s的向量中。

我需要将每个字节视为一个无符号整数(从0到255);并做一些算术运算。如何将矢量转换为矢量?


char a = 227;
cout << a;

打印?


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

打印-29


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

打印4294967267


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

打印?

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