【问题标题】:Why are random new lines appearing when I convert ASCII into hexadecimal?为什么我将 ASCII 转换为十六进制时会出现随机的新行?
【发布时间】:2017-04-01 14:42:34
【问题描述】:

所以我正在编写一个 C++ 程序来读取文本文件,找到每个字符的数字 ASCII 值并将其转换为十六进制,然后将其输出到屏幕上,但我会不断插入这些随机的新行出现以“C”结尾的十六进制值。

Screenshot of console output

这是我用来转换为十六进制的代码:

std::string HexConvert(char character) {
    char HEX[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    int ASCII = (int) character;
    if (ASCII > 255 || ASCII < 32) {
        return "20";
    } else {
        std::vector<char> binaryVec = binaryConvert(ASCII);
        std::string binaryVal(binaryVec.begin(), binaryVec.end());
        binaryVal = binaryVal.substr(binaryVal.length() - 8, 8);
        std::string bin1 = binaryVal.substr(0, 4);
        std::string bin2 = binaryVal.substr(4, 4);
        int hex1 = ((bin1[0] - 48)*8) + ((bin1[1] - 48)*4) + ((bin1[2] - 48)*2) + ((bin1[3] - 48)*1);
        int hex2 = ((bin2[0] - 48)*8) + ((bin2[1] - 48)*4) + ((bin2[2] - 48)*2) + ((bin2[3] - 48)*1);
        char hexVal[2] = { HEX[hex1], HEX[hex2] };
        std::string hexValue(hexVal);
        return hexValue;
    }
}

【问题讨论】:

  • 请不要发文字图片。

标签: c++ encoding hex ascii


【解决方案1】:

简单地废弃整个东西,并以正确的方式将ASCII 转换为十六进制会更快,而不是找出错误。

std::ostringstream o;

o << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << ASCII;

return o.str();

【讨论】:

  • 对于这个 ostringstream,我需要任何其他 #include 吗?
  • 你需要&lt;sstream&gt;&lt;iomanip&gt;,别以为还需要什么。如果有任何疑问,请查看您的 C++ 参考手册。
  • 似乎不喜欢 std::fill - 说它需要 3 个参数,但只给定一个。
  • 感谢它解决了问题。
【解决方案2】:

您忘记了字符串的终止空字节。

char hexVal[3] = { HEX[hex1], HEX[hex2], 0 };

如果没有终止 null,您将遇到未定义的行为;任何事情都可能发生。

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2011-11-21
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多