在单片机的编程中对于8位、16位、32位整数的分解与合并用的比较多,今天做了简要学习,后面还需要加以总结。
练习在VC++6.0编程环境中进行,源程序:
#include <stdio.h>
#include "string.h"
int main(int argc, char argv[])
{
unsigned int Data_Uint32=0x12345678;
unsigned short int Data_Uint16_1,Data_Uint16_2;
unsigned char Data_Uint8_1,Data_Uint8_2,Data_Uint8_3,Data_Uint8_4;
struct StructByte8{
unsigned char Byte01:1;
unsigned char Byte02:1;
unsigned char Byte03:1;
unsigned char Byte04:1;
unsigned char Byte05:1;
unsigned char Byte06:1;
unsigned char Byte07:1;
unsigned char Byte08:1;
} Test1;
unsigned char C1[]="A";
unsigned short int p16=(unsigned short int *)(&Data_Uint32);//定义16位的指针将32位地址强制转为16位,高位丢弃取低位
unsigned short int Data_Uint16_2p,Data_Uint16_1p;
printf("32位整数:0x%x\n",Data_Uint32);
printf("-------------------通过指针运算-------------------\n");
Data_Uint16_2p=*(unsigned short int *)p16;
Data_Uint16_1p=*((unsigned short int *)p16+1);
printf("转换后的16位整数:0x%x,0x%x\n",Data_Uint16_1p,Data_Uint16_2p);
Data_Uint8_1= *(unsigned char *)p16;
Data_Uint8_2= *((unsigned char *)p16+1);
Data_Uint8_3= *((unsigned char *)p16+2);
Data_Uint8_4= *((unsigned char *)p16+3);
printf("转换后的8位整数:0x%x,0x%x,0x%x,0x%x\n",Data_Uint8_1,Data_Uint8_2,Data_Uint8_3,Data_Uint8_4);
Data_Uint8_1=0;Data_Uint8_2=0;Data_Uint8_3=0;Data_Uint8_4=0;
//直接根据指针取值
//将32位的整数分解成两个16位的整数,再取低位的16位
//强制转换,丢弃高位的16位
//32位转16位
Data_Uint16_1=(unsigned short int)(Data_Uint32>>16);
Data_Uint16_2=(unsigned short int)Data_Uint32;
//32位转8位
Data_Uint8_1= (unsigned char)(Data_Uint32>>24);
Data_Uint8_2= (unsigned char)(Data_Uint32>>16);
Data_Uint8_3= (unsigned char)(Data_Uint32>>8);
Data_Uint8_4= (unsigned char)Data_Uint32;
printf("-------------------通过位运算-------------------\n");
printf("转换后的16位整数:0x%x,0x%x\n",Data_Uint16_1,Data_Uint16_2);
printf("转换后的8位整数:0x%x,0x%x,0x%x,0x%x\n",Data_Uint8_1,Data_Uint8_2,Data_Uint8_3,Data_Uint8_4);
printf("-------------------通过结构运算-------------------\n");
printf("字符A,ASCII为01000001,结构转换后的内容\n");
memcpy(&Test1, C1, sizeof(Test1));
printf("Test1.Byte08=%d \n",Test1.Byte08);
printf("Test1.Byte07=%d \n",Test1.Byte07);
printf("Test1.Byte06=%d \n",Test1.Byte06);
printf("Test1.Byte05=%d \n",Test1.Byte05);
printf("Test1.Byte04=%d \n",Test1.Byte04);
printf("Test1.Byte03=%d \n",Test1.Byte03);
printf("Test1.Byte02=%d \n",Test1.Byte02);
printf("Test1.Byte01=%d \n",Test1.Byte01);
Data_Uint8_1=0x89;Data_Uint8_2=0xAB;Data_Uint8_3=0xCD;Data_Uint8_4=0xEF;
printf("-------------------通过位运算合并-------------------\n");
Data_Uint16_1 = (unsigned short int)(Data_Uint8_1 << 8) | (unsigned short int)(Data_Uint8_2);
Data_Uint16_2 = (unsigned short int)(Data_Uint8_3 << 8) | (unsigned short int)(Data_Uint8_4);
Data_Uint32=(unsigned int) (Data_Uint16_1 << 16) | (unsigned int)(Data_Uint16_2);
printf("合并前的8位整数:0x%x,0x%x,0x%x,0x%x\n",Data_Uint8_1,Data_Uint8_2,Data_Uint8_3,Data_Uint8_4);
printf("合并后的16位整数:0x%x,0x%x\n",Data_Uint16_1,Data_Uint16_2);
printf("合并后的32位整数:0x%x\n",Data_Uint32);
return 0;
}
输出: