• 把十进制数(long型)分别以二进制和十六进制形式输出,不能使用printf系列。


    编程实现:把十进制数(long型)分别以二进制和十六进制形式输出,不能使用printf系列。

    实现了unsigned long型的转换。

    // 十进制转换为二进制,十进制数的每1bit转换为二进制的1位数字
    <pre lang="c" escaped="true" line="1">
    char *int_to_bin(unsigned long data)
    {
    int bit_num = sizeof(unsigned long) * 8;
    char *p_bin = new char[bit_num+1];
    p_bin[bit_num] = '';
    for (unsigned int i = 0; i < bit_num; ++i)
    {
    p_bin[i] = data << i >> (bit_num-1);
    if (p_bin[i] == 0)
    p_bin[i] = '0';
    else if (p_bin[i] == 1)
    p_bin[i] = '1';
    else
    p_bin[i] = 'a';
    }
    return p_bin;
    }
    </pre>

    // 十进制转换为十六进制,十进制数的每4bit转换为十六进制的1位数字
    <pre lang="c" escaped="true" line="1">
    char *int_to_hex(unsigned long data)
    {
    int bit_num = sizeof(unsigned long) * 8;
    char *p_hex = new char[sizeof(unsigned long)*8/4+3];
    p_hex[0] = '0';
    p_hex[1] = 'x';
    p_hex[bit_num/4+2] = '';
    char *p_tmp = p_hex + 2;
    for (unsigned int i = 0; i < bit_num/4; ++i)
    {
    p_tmp[i] = data << (4*i) >> (bit_num-4);
    if (p_tmp[i] >= 0 && p_tmp[i] <= 9)
    p_tmp[i] += '0';
    else if (p_tmp[i] >= 10 && p_tmp[i] <= 15)
    p_tmp[i] = p_tmp[i] - 10 + 'A';
    }
    return p_hex;
    }
    </pre>

  • 相关阅读:
    xshell入门及Linux常用命令
    C++之vector
    c++ 之 string
    引用 与 指针
    关于时间复杂度的计算以及相关概念
    位运算
    thymeleafDemo
    面试总结
    关于mvvm原理实现,模拟vue(3)-----发布订阅
    关于mvvm原理实现,模拟vue(2)-----模板编译
  • 原文地址:https://www.cnblogs.com/liweilijie/p/4984049.html
Copyright © 2020-2023  润新知