C语言10进制与16进制转换

在做一个模拟量模块的485通讯时,控制模拟量输出的协议格式是将需要输出的真实电压值(0~10V)数据扩大1000倍后转换成16进制数据,一般情况数据转换后为4位16进制数据(0xWXYZ),协议需要的是两个2位的数据0xWX和0xYZ,由此写出以下代码

#include <stdio.h>

unsigned int DATA_HEX;
unsigned int DATA_H;
unsigned int DATA_L;
unsigned int HEX_TEMP[] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F};
unsigned int HEX_ARR[4];//我的数据只需要4位16进制数据

void HEX_TO_DEC(unsigned int val)
{
    unsigned int i = 0;
    while(val)
    {
        HEX_ARR[i++] = HEX_TEMP[val%16];
        val /= 16;
    }
    DATA_HEX = HEX_ARR[3]*0x1000 + HEX_ARR[2]*0x0100 + HEX_ARR[1]*0x0010 + HEX_ARR[0];//4位16进制
    DATA_H = HEX_ARR[3]*0x10 + HEX_ARR[2];//2位16进制
    DATA_L = HEX_ARR[1]*0x10 + HEX_ARR[0];
}

int main()
{
    unsigned int val = 5036;//待转换数据,16进制表示位0x13AC
    
    HEX_TO_DEC(val);//转换

    //打印结果
    printf("HEX_ARR[3]:%X\n", HEX_ARR[3]);
    printf("HEX_ARR[2]:%X\n", HEX_ARR[2]);
    printf("HEX_ARR[1]:%X\n", HEX_ARR[1]);
    printf("HEX_ARR[0]:%X\n", HEX_ARR[0]);
    printf("DATA_HEX:%X\n", DATA_HEX);
    printf("DATA_H:%X\n", DATA_H);
    printf("DATA_H:%X\n", DATA_H);
}

运行结果如下所示