對於char型,它所表示的范圍為-128~+127,假設有如下語句:
char data[3] = {0xab, 0xcd, 0xef};
初始化之后想打印出來,cout << data[0] << data[1] << data[2]; 發現都是亂碼,沒有按十六進制輸出。
在ASCII中,一共定義了128個字符,其中33個無法顯示,為0~31和127,32到126為可顯示字符,當使用cout輸出一個char型字符時,如果是可顯示范圍內,則輸出相應可顯示字符,其余的都輸出亂碼。
如果我們要使字符按十六進制輸出,可以使用hex,但是發現cout << hex << data[0];沒有輸出十六進制,因為hex只對整數起作用,將data[0]轉換為int,cout << hex << int(data[0]); 發現輸出的結果前面帶了很多f。因為data[0]是有符號數,最高位為1時,轉換為int時,其余位都為1,cout << hex << (unsigned int) (unsigned char)data[0];結果正確。
對於小於16的char,輸出只顯示一位,如果希望都顯示兩位,可以在輸出前設置cout << setfill('0') << setw(2);
#include <iostream> #include <iomanip> using namespace std; int main() { std::cout << "Hello World!\n"; char n = 222; cout << hex << setfill('0') << setw(2) << (unsigned int)(unsigned char)(n)<<endl; cout << hex << setfill('0') << setw(2) << (int)n; }
輸出到文件:
#include <iostream> #include <cstdio>#include <fstream> using namespace std; ofstream file; file.open("commands_.log", std::ios_base::trunc ); auto data = playback->serialize(); //file.write(data->data(), data->size()); { int len = data->size(); const char* c = static_cast<const char*>(data->data()); for (int i = 0; i < len;) { file << ",0x" << hex << setfill('0') << setw(2) << (unsigned int)(unsigned char)c[i]; i++; if (i % 16 == 0) file << endl; } } }
也可以用 std::stoi()
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <iomanip>
int main() {
std::string line;
std::vector<std::string> hex_array;
std::ifstream file("e:/skp.txt");
//read string in format:" FF F0 EA 33 "
while (std::getline(file, line)) {
std::istringstream iss(line);
std::string hex_str;
while (iss >> hex_str) {
//std::cout <<hex_str<< std::endl;
hex_array.push_back(hex_str);
}
}
//output string as char byte: sucha as 65 to a.
std::cout << "total size:" << hex_array.size() << std::endl;
//print to readable charactor
for (auto byte_str : hex_array) {
char byte = static_cast<char>(std::stoi(byte_str, nullptr, 16));
std::cout << byte;
//std::cout << "0x" << std::hex << byte_str << ", ";
}
std::cout << std::endl;
//same as above. just output to a file as bin dump:
std::ofstream output_file("e:/output.txt");
for (auto byte_str : hex_array) {
char byte = static_cast<char>(std::stoi(byte_str, nullptr, 16));
output_file << byte;
//std::cout << "0x" << std::hex << byte_str << ", ";
}
output_file << std::endl;
//output value as hex format:
for (auto byte_str : hex_array) {
char byte = static_cast<char>(std::stoi(byte_str, nullptr, 16));
auto hex_value = std::stoi(byte_str, nullptr, 16);
std::cout << "0x" << std::hex << std::setfill('0') << std::setw(2) << hex_value << ", ";
}
std::cout << std::endl;
return 0;
}