C++實(shí)現(xiàn)二進(jìn)制字符串與十六進(jìn)制字符串相互轉(zhuǎn)換
以下是一個將二進(jìn)制字符串轉(zhuǎn)換為十六進(jìn)制字符串的C++函數(shù):
#include <string>
#include <unordered_map>
std::string binaryToHex(const std::string& binaryStr) {
// 預(yù)定義的二進(jìn)制到十六進(jìn)制映射
std::unordered_map<std::string, char> binToHex = {
{"0000", '0'}, {"0001", '1'}, {"0010", '2'}, {"0011", '3'},
{"0100", '4'}, {"0101", '5'}, {"0110", '6'}, {"0111", '7'},
{"1000", '8'}, {"1001", '9'}, {"1010", 'A'}, {"1011", 'B'},
{"1100", 'C'}, {"1101", 'D'}, {"1110", 'E'}, {"1111", 'F'}
};
std::string result;
std::string paddedBinary = binaryStr;
// 在二進(jìn)制字符串前面補(bǔ)0,使其長度成為4的倍數(shù)
int remainder = paddedBinary.length() % 4;
if (remainder != 0) {
paddedBinary = std::string(4 - remainder, '0') + paddedBinary;
}
// 每4位一組進(jìn)行轉(zhuǎn)換
for (size_t i = 0; i < paddedBinary.length(); i += 4) {
std::string group = paddedBinary.substr(i, 4);
result += binToHex[group];
}
return result;
}使用示例:
#include <iostream>
int main() {
std::string binary1 = "1101"; // 二進(jìn)制 1101
std::string binary2 = "101011"; // 二進(jìn)制 101011
std::string binary3 = "111100001010"; // 二進(jìn)制 111100001010
std::cout << binary1 << " -> " << binaryToHex(binary1) << std::endl; // 輸出: D
std::cout << binary2 << " -> " << binaryToHex(binary2) << std::endl; // 輸出: 2B
std::cout << binary3 << " -> " << binaryToHex(binary3) << std::endl; // 輸出: F0A
return 0;
}如果你想要一個更簡潔的版本,也可以使用位運(yùn)算的方法:
#include <string>
#include <sstream>
std::string binaryToHexBitwise(const std::string& binaryStr) {
// 先將二進(jìn)制字符串轉(zhuǎn)換為整數(shù)
unsigned long long decimal = 0;
for (char c : binaryStr) {
decimal = (decimal << 1) | (c - '0');
}
// 再將整數(shù)轉(zhuǎn)換為十六進(jìn)制字符串
std::stringstream ss;
ss << std::hex << std::uppercase << decimal;
return ss.str();
}注意事項:
- 第一個方法使用查表法,適合處理任意長度的二進(jìn)制字符串
- 第二個方法使用位運(yùn)算,更簡潔但可能受限于整數(shù)類型的最大長度
- 兩個函數(shù)都會自動處理前導(dǎo)零的情況
- 輸出使用大寫字母(A-F),如果需要小寫字母,可以將映射中的字母改為小寫
選擇哪種方法取決于你的具體需求:
- 如果需要處理很長的二進(jìn)制字符串,建議使用第一種方法
- 如果二進(jìn)制字符串長度在64位以內(nèi),第二種方法更簡潔高效
以下是一個將十六進(jìn)制字符串轉(zhuǎn)換為二進(jìn)制字符串的C++函數(shù):
#include <string>
#include <unordered_map>
std::string hexToBinary(const std::string& hexStr) {
// 預(yù)定義的十六進(jìn)制到二進(jìn)制映射
std::unordered_map<char, std::string> hexToBin = {
{'0', "0000"}, {'1', "0001"}, {'2', "0010"}, {'3', "0011"},
{'4', "0100"}, {'5', "0101"}, {'6', "0110"}, {'7', "0111"},
{'8', "1000"}, {'9', "1001"}, {'A', "1010"}, {'B', "1011"},
{'C', "1100"}, {'D', "1101"}, {'E', "1110"}, {'F', "1111"},
{'a', "1010"}, {'b', "1011"}, {'c', "1100"}, {'d', "1101"},
{'e', "1110"}, {'f', "1111"}
};
std::string result;
for (char c : hexStr) {
// 跳過空格等無關(guān)字符
if (c == ' ' || c == '\t' || c == '\n') {
continue;
}
// 檢查是否為有效的十六進(jìn)制字符
if (hexToBin.find(c) != hexToBin.end()) {
result += hexToBin[c];
} else {
// 如果遇到無效字符,可以拋出異常或返回空字符串
throw std::invalid_argument("Invalid hexadecimal character: " + std::string(1, c));
// 或者返回空字符串:return "";
}
}
// 移除前導(dǎo)零(可選)
size_t firstOne = result.find_first_not_of('0');
if (firstOne != std::string::npos) {
result = result.substr(firstOne);
} else {
// 如果全是零,返回"0"
result = "0";
}
return result;
}使用示例:
#include <iostream>
#include <stdexcept>
int main() {
try {
std::string hex1 = "D"; // 十六進(jìn)制 D
std::string hex2 = "2B"; // 十六進(jìn)制 2B
std::string hex3 = "F0A"; // 十六進(jìn)制 F0A
std::string hex4 = "1F"; // 十六進(jìn)制 1F
std::cout << hex1 << " -> " << hexToBinary(hex1) << std::endl; // 輸出: 1101
std::cout << hex2 << " -> " << hexToBinary(hex2) << std::endl; // 輸出: 101011
std::cout << hex3 << " -> " << hexToBinary(hex3) << std::endl; // 輸出: 111100001010
std::cout << hex4 << " -> " << hexToBinary(hex4) << std::endl; // 輸出: 11111
// 測試小寫字母
std::cout << "a" << " -> " << hexToBinary("a") << std::endl; // 輸出: 1010
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}如果你想要一個不使用異常處理的版本:
#include <string>
#include <unordered_map>
std::string hexToBinarySafe(const std::string& hexStr) {
std::unordered_map<char, std::string> hexToBin = {
{'0', "0000"}, {'1', "0001"}, {'2', "0010"}, {'3', "0011"},
{'4', "0100"}, {'5', "0101"}, {'6', "0110"}, {'7', "0111"},
{'8', "1000"}, {'9', "1001"}, {'A', "1010"}, {'B', "1011"},
{'C', "1100"}, {'D', "1101"}, {'E', "1110"}, {'F', "1111"},
{'a', "1010"}, {'b', "1011"}, {'c', "1100"}, {'d', "1101"},
{'e', "1110"}, {'f', "1111"}
};
std::string result;
for (char c : hexStr) {
if (c == ' ' || c == '\t' || c == '\n') {
continue;
}
auto it = hexToBin.find(c);
if (it != hexToBin.end()) {
result += it->second;
} else {
// 遇到無效字符時返回空字符串
return "";
}
}
// 處理全零的情況
if (result.empty()) {
return "0";
}
// 移除前導(dǎo)零
size_t firstOne = result.find_first_not_of('0');
if (firstOne != std::string::npos) {
result = result.substr(firstOne);
} else {
result = "0";
}
return result;
}函數(shù)特點(diǎn):
- 大小寫支持:同時支持大寫和小寫十六進(jìn)制字符
- 空格處理:自動跳過空格、制表符和換行符
- 錯誤處理:提供異常處理和安全返回兩種方式
- 前導(dǎo)零處理:可選是否移除前導(dǎo)零
- 完整性:每個十六進(jìn)制字符轉(zhuǎn)換為4位二進(jìn)制
注意事項:
- 如果需要保留前導(dǎo)零,可以注釋掉移除前導(dǎo)零的代碼部分
- 可以根據(jù)需要調(diào)整錯誤處理策略(拋出異常或返回特定值)
- 函數(shù)會驗(yàn)證輸入的有效性,確保只處理合法的十六進(jìn)制字符
到此這篇關(guān)于C++實(shí)現(xiàn)二進(jìn)制字符串與十六進(jìn)制字符串相互轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)C++進(jìn)制字符串轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++實(shí)現(xiàn)LeetCode(49.群組錯位詞)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(49.群組錯位詞),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
從匯編看c++中默認(rèn)構(gòu)造函數(shù)的使用分析
c++中,如果為一個類沒有明確定義一個構(gòu)造函數(shù),那么,編譯器就會自動合成一個默認(rèn)的構(gòu)造函數(shù)。下面,通過匯編程序,來看一下其真實(shí)情況2013-05-05

