Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15367139
  • 博文数量: 2005
  • 博客积分: 11986
  • 博客等级: 上将
  • 技术积分: 22535
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-17 13:56
文章分类

全部博文(2005)

文章存档

2014年(2)

2013年(2)

2012年(16)

2011年(66)

2010年(368)

2009年(743)

2008年(491)

2007年(317)

分类: LINUX

2008-03-17 16:08:50

#include <stdio.h>

void bytes2hex(int value, char *out_buf, char bytes)
{
    char *p;
    
    inline char bcd2hex(char BCD)
    {
        return (BCD > 9) ? (BCD-10+'A'):(BCD+'0');
    }
    inline void char2hex(char value,char **out)
    {
        *(*out)++ = bcd2hex(value >> 4);
        *(*out)++ = bcd2hex(value & 0x0f);
    }
    
    p = out_buf;
    *p++ = '0';
    *p++ = 'x';
    if(bytes > 3)char2hex(value >> 24,&p);
    if(bytes > 2)char2hex(value >> 16,&p);
    if(bytes > 1)char2hex(value >> 8,&p);
    char2hex(value &0xff,&p);
    *p = 0;
}

int main(int argc,char *argv[])
{
    int value;
    char out_str[12];

    value = 0x12345678;
    
    bytes2hex(value,out_str,sizeof(char));
    printf("-sizeof(char)---%s----\n",out_str);

    bytes2hex(value,out_str,sizeof(short));
    printf("-sizeof(short)---%s----\n",out_str);

    bytes2hex(value,out_str,3);
    printf("-3---%s----\n",out_str);

    bytes2hex(value,out_str,sizeof(long));
    printf("-sizeof(long)---%s----\n",out_str);
}

阅读(1129) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~