zoukankan      html  css  js  c++  java
  • 使用移位操作把十进制转换为二进制与十六进制字符串输出

      函数原型:

    //转二进制
    char *ConvertTo2String(long number);
    //转十六进制
    char *ConvertTo16String(long number);
    

      思路:

      转换二进制很简单,二步操作即可完成,

             1:循环对数字1左移31-i(i={0,31})位(从高位开始的),再与把number作位与操作,

           2:再把刚才的结果通过右移31-i  (i={0,31}) 位得出每一位是否为0还是1,

      这样就得到了每一位的二进制位,再把这些二进制位拼成字符串就OK了!

    char *ConvertTo2String(long number)
    {
         char *output = NULL;
         output = (char*)malloc(33);    //include '\0'
         
         int i = 0;
         for(;i<32;i++)
         {
             output[i] = number & (1<<31-i);
             output[i] = output[i] >> 31-i;
             output[i] = (output[i] == 0) ? '0' : '1';
         }
         output[i] = '\0';
         return output
    }
    

      转换十六进制麻烦一点,要考虑字母的情况,

    char * ConvertTo16String(long number)
    {
        char *output= NULL;
        char *temp = NULL;
    
        output= (char*) malloc(11);
    
        output[0] = '0';
        output[1] = 'x';
        output[10] = '\0';
        temp = output+ 2;
    
        for(int i = 0; i<8; i++)
        {
            temp[i] = (char)(number<< 4 * i >> 28);    //先左移4*i,再右移28,每一次处理4位
            temp[i] = temp[i]>=0 ? temp[i] : temp[i]+16;    //为转换为A~F的字母作准备
            temp[i] = temp[i] < 10 ? temp[i]+48 : temp[i]+55;   //转字母
        }
       
        return output;
    }
    
  • 相关阅读:
    Wolfram常用计算
    soapUI接口关联教程
    时间序列预测线上充值数据
    基于MySQL分析线上充值留存率
    更改用户资料需要完善脚本
    MySQL建立RFM模型
    Scrcpy使用入门
    虾皮Shopee社招面经分享(大数据开发方向),附内推方式
    MySQL Binlog 解析工具 Maxwell 详解
    MySQL Binlog 介绍
  • 原文地址:https://www.cnblogs.com/repository/p/1943460.html
Copyright © 2011-2022 走看看