C语言整型数据转十六进制数据(防止溢出)

#include <stdio.h>
#include <string.h>

void InttoHex(char *buf, int data, int byteNum) //整型转十六进制
{
        int i;

        for(i=0; i<byteNum; i++)
        {
                if(i < (byteNum-1)) 
                {
                        buf[i] = data >> (8*(byteNum-i-1)); 
                }
                else
                {
                        buf[i] = data % 256;
                }
        }
}

void main()
{
        int a = 1000;
        char str[128];
        unsigned char buf[128];         //加unsigned 防止char型数据溢出 char范围最高000~127

        memset(str, 0, 128);
        memset(buf, 0, 128);

        InttoHex(str, a, 4);
        InttoHex(buf, a, 4);

        printf("%02x %02x %02x %02x\n", str[0],str[1],str[2],str[3]);   //str[3]数据溢出
        printf("%02x %02x %02x %02x\n", buf[0],buf[1],buf[2],buf[3]);   //buf[3]数据正常

        return;
}

  

猜你喜欢

转载自www.cnblogs.com/quliuliu2013/p/12624014.html
今日推荐