简体   繁体   English

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

[英]How to convert Hex in string format to Hex format

So i have a code that converts binary input to hex in string format:所以我有一个将二进制输入转换为字符串格式的十六进制的代码:

#include <cstring>
#include <iostream>
#include <string>
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;
}

(ex. input: 11011 , output: 1B ) (例如输入: 11011 ,输出: 1B

But i cant figure out how can i represent that in hex format(for ex. i can create hex variables using uint8_t a = 0x1b and print that using printf("%x", a) . I would appreciate if you can help me.但我不知道如何以十六进制格式表示它(例如,我可以使用uint8_t a = 0x1b创建十六进制变量并使用printf("%x", a)打印它。如果你能帮助我,我将不胜感激。

To parse the input, the standard std::stoul allows to set the base as parameter.为了解析输入,标准std::stoul允许将基数设置为参数。 For base 2:对于基数 2:

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

Than you can print it as hex using either比您可以使用任何一个将其打印为十六进制

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

or或者

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

See https://godbolt.org/z/5j45W9EG6 .请参阅https://godbolt.org/z/5j45W9EG6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM