[英]how to print Ascii code of a string in c++
我有一個字符串,我想打印每個部分的ASCII碼的十六進制值。 例如,如果字符串為“ 0200”,則輸出將為30323030
。
這是我的代碼:
string bit_pattern;
bit_pattern = "5678008180000000";
cout << hex << bit_pattern;
但它打印5678008180000000
而不是35363738303038313830303030303030
我該如何解決???
您可以使用以下內容
for (int i=0; i<bit_pattern.length(); i++)
cout << hex << (int)bit_pattern[i];
按char打印ascii值(十六進制格式)char。
您只是向std::cout
發送相同的std::string
。 僅僅發送hex
操縱器不會神奇地轉換所有這些字符。
我承認這完全是矯kill過正,但我很無聊:
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
class ascicodes
{
std::ostringstream ss;
public:
friend std::ostream& operator <<(std::ostream& os, const ascicodes& obj)
{
os << obj.ss.str();
return os;
}
ascicodes(const std::string& s)
{
ss << std::hex << std::setfill('0');
std::for_each(s.begin(), s.end(),
[this](char ch)
{
ss << std::setw(2) << static_cast<unsigned int>(ch);
});
}
};
int main()
{
std::string bit_pattern = "5678008180000000";
std::cout << ascicodes(bit_pattern) << std::endl;
std::cout << ascicodes("A completely different string") << std::endl;
return 0;
}
產量
35363738303038313830303030303030
4120636f6d706c6574656c7920646966666572656e7420737472696e67
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.