[英]How to convert Hex in string format to Hex 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;
}
(例如輸入: 11011
,輸出: 1B
)
但我不知道如何以十六進制格式表示它(例如,我可以使用uint8_t a = 0x1b
創建十六進制變量並使用printf("%x", a)
打印它。如果你能幫助我,我將不勝感激。
為了解析輸入,標准std::stoul
允許將基數設置為參數。 對於基數 2:
unsigned long input = std::stoul(str, nullptr, 2);
比您可以使用任何一個將其打印為十六進制
std::cout << std::hex << input << '\n';
或者
std::printf("%lx\n", input);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.