将char转换为无符号整数

时间:2015-11-30 20:46:58

标签: c++

我将一个巨大的二进制文件读入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;

打印?

1 个答案:

答案 0 :(得分: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;
}