如何将字符串格式的十六进制转换为十六进制格式

分享于2022年07月17日 c++ 问答
【问题标题】:如何将字符串格式的十六进制转换为十六进制格式(How to convert Hex in string format to Hex format)
【发布时间】:2022-07-08 23:39:16
【问题描述】:

所以我有一个代码可以将二进制输入转换为字符串格式的十六进制:

#include 
#include 
#include 
using namespace std;

int main() {
    string binary[16] = {"0000", "0001", "0010", "0011", "0100", "0101",
                         "0110", "0111", "1000", "1001", "1010", "1011",
                         "1100", "1101", "1110", "1111"};
    char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
                    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    string binaryInput;
    cin >> binaryInput;
    int inputLen = binaryInput.length();
    string add(4 - inputLen % 4, '0');
    if (binaryInput.length() / 4 != 0) {
        binaryInput = add + binaryInput;
    }
    inputLen = binaryInput.length();

    cout << "converted input: " << binaryInput << endl;
    cout << "converted input length: " << inputLen << endl;

    int intInput = stoi(binaryInput);
    string hexEq = "";

    for (int i = 0; i < inputLen / 4; i++) {
        string quad = "";

        for (int k = 0; k < 4; k++) {
            if (intInput % 10) {
                quad = '1' + quad;
            } else {
                quad = '0' + quad;
            }
            intInput /= 10;
        }

        for (int j = 0; j < 16; j++) {
            if (quad == binary[j]) {
                hexEq = hex[j] + hexEq;
                break;
            }
        }
    }

    cout << "input converted to hex: " << hexEq << endl;
}

(例如输入: 11011 ,输出: 1B

但我不知道如何以十六进制格式表示它(例如,我可以使用 uint8_t a = 0x1b 创建十六进制变量并使用 printf("%x", a) 打印它。如果您能帮助我,我将不胜感激。

  • if(binaryInput.length()/4!=0) ==> if(binaryInput.length() % 4 != 0)
  • 您在寻找 std::cout << std::hex << a; 吗?
  • 我认为这让你正在做的事情变得很复杂。取4位,在 binary 数组中搜索,使用索引从 hex 数组添加到 hexEq

【解决方案1】:

为了解析输入,标准 std::stoul 允许将基数设置为参数。对于基数 2:

unsigned long input = std::stoul(str, nullptr, 2);

您可以使用任何一种方式将其打印为十六进制

std::cout << std::hex << input << '\n';

std::printf("%lx\n", input);

https://godbolt.org/z/5j45W9EG6

  • 谢谢,现在看起来很容易,我希望我早点知道 std::stoul。
  • stoul 函数中的 2 也看起来像数字系统,所以如果我说 2 是二进制,8 是八进制,10 是十进制,16 是十六进制,是真的吗?
  • 是的,确实如此,但您最好阅读 en.cppreference.com/w/cpp/string/basic_string/stoul 的完整文档