十六进制转为二进制 c++实现
时间: 2024-10-31 11:07:09 浏览: 0
十六进制转换成二进制在C++中通常通过循环和位操作来实现。首先,你需要将每个十六进制字符转换为其对应的四位二进制数,因为十六进制有16种可能的值,对应于二进制的4位。下面是一个简单的示例:
```cpp
#include <iostream>
#include <string>
std::string hexToBinary(const std::string& hexStr) {
std::string binaryStr = "";
for (size_t i = 0; i < hexStr.length(); ++i) {
char hexChar = hexStr[i];
if (hexChar >= '0' && hexChar <= '9') {
binaryStr += std::to_string(hexChar - '0'); // 对于数字直接转换
} else if (hexChar >= 'A' && hexChar <= 'F') { // 对于字母A-F,加10
binaryStr += std::to_string(hexChar - 'A' + 10);
} else if (hexChar >= 'a' && hexChar <= 'f') { // 对于小写字母a-f,也加10
binaryStr += std::to_string(hexChar - 'a' + 10);
}
// 每次添加四位二进制数
binaryStr.insert(binaryStr.begin(), "0000", '0');
}
return binaryStr;
}
int main() {
std::string hexInput = "1A";
std::string binaryOutput = hexToBinary(hexInput);
std::cout << "Hex to Binary: " << binaryOutput << std::endl;
阅读全文