整数转换成16进制字符串的程序

本文介绍了一个将无符号整数转换为十六进制字符串的 C 语言函数 itoa_hex。该函数接受一个无符号整数和一个字符缓冲区作为参数,并将整数转换为对应的十六进制形式存储在缓冲区内。文章还提供了一个简单的 main 函数用于演示如何使用此函数。
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. char * itoa_hex(unsigned int data,char * hbuff)
  4. {
  5.     unsigned char * p=(unsigned char *)(&data);
  6.     int len=sizeof(data);
  7.     
  8.     static const char hex_map[]="0123456789ABCDEF";
  9.     static const bool lit_end=*(char*)(&len)==len;
  10.     
  11.     int counter=0;
  12.     if(lit_end)
  13.     {
  14.         for(counter=len;counter>0;--counter)
  15.         {
  16.             hbuff[(len-counter)<<1]=hex_map[*(p+counter-1)>>4];
  17.             hbuff[((len-counter)<<1)|1]=hex_map[(*(p+counter-1))&0XF];
  18.         }
  19.     }
  20.     else
  21.     {
  22.         for(;counter<len;++counter)
  23.         {
  24.             hbuff[counter<<1]=hex_map[*(p+counter-1)>>4];
  25.             hbuff[(counter<<1)|1]=hex_map[*(p+counter-1)|0X0F];
  26.         }
  27.     }
  28.     return hbuff;
  29. }
  30. int main(int argc, char * argv[])
  31. {
  32.     char buff[32]="";
  33.     itoa_hex(atoi(argv[1]),buff);
  34.     printf("%s/n",buff);
  35.     return 0;
  36. }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值