unsigned char类型和unsigned int类型相互转化

写单片机程序的时候经常遇到unsigned char类型和unsigned int类型相互转化

下面写一个简单的例子实现互相转化的过程,比较简单,直接上代码。

#include<stdio.h>
#define uint8 unsigned char
#define uint32 unsigned int

#define BREAK_UINT32( var, ByteNum ) \
          (uint8)((uint32)(((var) >>((ByteNum) * 8)) & 0x00FF))

#define BUILD_UINT32(Byte0, Byte1, Byte2, Byte3) \
          ((uint32)((uint32)((Byte0) & 0x00FF) \
          + ((uint32)((Byte1) & 0x00FF) << 8) \
          + ((uint32)((Byte2) & 0x00FF) << 16) \
          + ((uint32)((Byte3) & 0x00FF) << 24)))
int main(){
    uint8 temp[4] = {0x01,0x02,0x03,0x04};
    uint32 tevalu = 0;
    
    tevalu = BUILD_UINT32(temp[0],temp[1],temp[2],temp[3]);
    printf("---%08x-------\n",tevalu);
    
    uint8 temp2[4] = {0x0};
    temp2[0] = BREAK_UINT32(tevalu,0);
    temp2[1] = BREAK_UINT32(tevalu,1);
    temp2[2] = BREAK_UINT32(tevalu,2);
    temp2[3] = BREAK_UINT32(tevalu,3);
    
    printf("--%02x--%02x--%02x--%02x--\n",temp2[0],temp2[1],temp2[2],temp2[3]);
    
    return 0;
}

运行结果:

还有一些常用的宏定义,这里加上

#define BUILD_UINT16(loByte, hiByte) \
          ((uint16)(((loByte) & 0x00FF) + (((hiByte) & 0x00FF) << 8)))

#define HI_UINT16(a) (((a) >> 8) & 0xFF)
#define LO_UINT16(a) ((a) & 0xFF)

#define BUILD_UINT8(hiByte, loByte) \
          ((uint8)(((loByte) & 0x0F) + (((hiByte) & 0x0F) << 4)))

#define HI_UINT8(a) (((a) >> 4) & 0x0F)
#define LO_UINT8(a) ((a) & 0x0F)

猜你喜欢

转载自blog.csdn.net/farsight_2098/article/details/88743495
今日推荐