簡體   English   中英

將字符轉換為無符號整數

[英]Converting char to unsigned integer

我將一個巨大的二進制文件讀入了一個char向量。

我需要將每個字節視為一個無符號整數(從 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM