用C++实现十进制到十六进制的两种转换方法

来源:互联网 发布:网络教育学费多少 编辑:程序博客网 时间:2024/05/24 04:30
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

string itos(int n)
{
    ostringstream o;
    o << n;
    return o.str();
}

string ctos(char n)
{
    ostringstream o;
    o << n;
    return o.str();
}

//采用移位运算,每四位转换为一个十六进制数
void invert_1(vector<string> &v1, int n)
{
  int bytenum = sizeof(int);
  int m = 0;

  for(int i = 2*bytenum-1; i!=-1; --i)
    {
      m = n;
      m = (m >> i*4) & ~(~0 << 4);
    
       if(m>=0 && m<=9)
         v1.push_back(itos(m));
       else
         v1.push_back(ctos(char(m+55)));
     }
}


//用16去除输入的十进制数
void invert_2(vector<string> &v2, int n)
{
  int shang = 0;  //商
  int yushu = 0;  //余数
  int value = 1;  //权值
  
  while(value <= n)
   {
     value = value * 16;
     yushu = n % value;
     shang = yushu * 16 / value;
     
       if(shang>=0 && shang<=9)
         v2.push_back(itos(shang));
       else
         v2.push_back(ctos(char(shang+55)));
   }
  
  reverse(v2.begin(),v2.end());        //将向量中的元素倒置
}

void print(vector<string> &v)
{
 
  bool first = true;    //判断0要不要输出
  cout << "the result is: ";
  for(vector<string>::size_type it = 0; it != v.size(); ++it)
   {
      if(v[it]=="0" && first == true)
         continue;
     else
        first = false;

     if(first == false)
       cout << v[it];
   }    

  cout << endl;
}

int main()
{
  vector<string> v1;
  vector<string> v2;

  int input = 0;

  cout << "please input a decimal data: ";
  cin >> input;

  invert_1(v1,input);
  invert_2(v2,input);

  print(v1);
  print(v2);

  return 0;
}
原创粉丝点击