21xrx.com
2025-04-28 11:36:58 Monday
文章检索 我的文章 写文章
C++代码:二进制转十六进制
2023-07-05 06:31:40 深夜i     40     0
C++ 代码 二进制 十六进制 转换

在计算机科学中,进制转换是一项重要的基础知识。进制转换可以将一种进制的数值表示转换为另一种进制的数值表示。其中,二进制转十六进制是一个比较常见的转换方式。在C++语言中实现二进制转十六进制的代码如下:

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
  string binary; // 二进制数
  string hex; // 十六进制数
  cout << "请输入一个二进制数:" << endl;
  cin >> binary;
  // 如果二进制数不是4的倍数,则在前面加0,直到二进制数长度是4的倍数
  while(binary.length() % 4 != 0)
  {
    binary = '0' + binary;
  }
  // 将二进制数转换为十六进制数
  for(int i = 0; i < binary.length(); i += 4)
  {
    string temp = binary.substr(i, 4);
    if(temp == "0000") hex += '0';
    else if(temp == "0001") hex += '1';
    else if(temp == "0010") hex += '2';
    else if(temp == "0011") hex += '3';
    else if(temp == "0100") hex += '4';
    else if(temp == "0101") hex += '5';
    else if(temp == "0110") hex += '6';
    else if(temp == "0111") hex += '7';
    else if(temp == "1000") hex += '8';
    else if(temp == "1001") hex += '9';
    else if(temp == "1010") hex += 'A';
    else if(temp == "1011") hex += 'B';
    else if(temp == "1100") hex += 'C';
    else if(temp == "1101") hex += 'D';
    else if(temp == "1110") hex += 'E';
    else if(temp == "1111") hex += 'F';
  }
  // 输出十六进制数
  cout << "十六进制数为:" << hex << endl;
  return 0;
}

以上代码中,先要求用户输入一个二进制数并存储到字符串变量`binary`中。然后,判断二进制数的长度是否是4的倍数,如果不是则在前面加0,直到长度是4的倍数。接着,将二进制数每4个一组分成若干个子串,并将每个子串转换为相应的十六进制数存储到字符串变量`hex`中。最后,输出转换后的十六进制数`hex`。

运行以上代码,可以得到如下输出:

请输入一个二进制数:
10100111
十六进制数为:A7

通过以上例子可以看出,二进制数`10100111`被转换为十六进制数`A7`。这说明C++代码中的二进制转十六进制的实现是正确的。

总结

二进制转十六进制是一项基础的进制转换操作。在C++语言中,可以通过字符串变量来实现二进制转十六进制的操作。在对二进制数进行转换时,需要注意二进制数长度不是4的倍数的情况。通过以上的代码示例,我们可以更好地理解二进制转十六进制的操作方法。

  
  

评论区