【问题标题】:how to print Ascii code of a string in c++如何在 C++ 中打印字符串的 Ascii 代码
【发布时间】:2014-02-07 08:24:25
【问题描述】:

我有一个字符串,我想打印每个部分 ascii 代码的十六进制值。 例如,如果字符串为“0200”,则输出将为30323030

这是我的代码:

string bit_pattern;
bit_pattern = "5678008180000000";
cout << hex << bit_pattern;

但它打印 5678008180000000 而不是 35363738303038313830303030303030 怎么解决???

【问题讨论】:

  • 对于字符串中的每个char,转换为unsigned int 并发送到hex - 操纵cout
  • 我相信您可以将其转换为 hashCode()。 hashcode和ascii之间有联系

标签: c++ string ascii


【解决方案1】:

你可以使用下面的

for (int i=0; i<bit_pattern.length(); i++)
    cout << hex << (int)bit_pattern[i];

按字符打印 ascii 值(十六进制格式)。

【讨论】:

    【解决方案2】:

    您只是将相同的std::string 权限发送给std::cout。仅仅发送 hex 操纵器不会神奇地转换所有这些字符。

    我承认这完全是矫枉过正,但我​​很无聊:

    #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
    

    【讨论】:

    • @DieterLücking 是的,我在课堂上忘记了。我打算在那里。你认为她在主要方面更好,只是在课堂上使用小数?它必须在值插入之前,这是我提到它的唯一原因。
    • 以及如何让人们相信这比使用旧 C 样式转换的 herohuyongtao 中的短样本更好,但仍能产生正确的结果?
    • @SChepurin 我不知道我必须说服任何人它“更好”;只是这是一种方法,特别是如果您需要经常使用大量具有预先存在的流输出的代码来执行此操作。此外,他的样本不处理高 ascii。对于 127 以上的字符,符号扩展将不愉快。
    • @WhozCraig - 我认为,这可以算作“足够有说服力”。
    • @DieterLücking 是 std::hex 粘性?我永远不记得哪个是哪个不是(除了setw,哪个是not(如果我没记错的话)。它们是两个不同的流,所以它仍然必须在课堂上,但只是好奇.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2016-06-21
    • 2021-07-01
    • 1970-01-01
    • 2020-02-01
    • 2015-06-04
    相关资源
    最近更新 更多