导航

面试记录04:将16进制数组元素合并成一个16进制数

Posted on 2020-06-27 00:01  ErgoCogito  阅读(1127)  评论(0编辑  收藏  举报

题目:

用C语言实现将数组如 unsigend char a[4]={0×11,0×22,0×33,0×44},转换成一个32位的整型数i=0×11223344;
在以下语句基础上完成程序设计

unsigned char a[4]={0×11,0×22,0×33,0×44};
int i = 0;

答案:

方法一:

1 int main() 
2 {
3     usigned char a[4]  = {0x11, 0x22, 0x33, 0x44};
4     unsigned int result = 0;
5     for (int i=0; i<4; i++) 
6     {
7         result = result << 8 | a[i];//十六进制的1位相当于二进制的4位,所以二进制左移8位相当于十六进制左移2位
8     }
9 }

方法二:

1 int main() 
2 {
3     unsigned char a[4]  = {0x12, 0x34, 0x56, 0x78};
4     unsigned int result = 0;
5     int i = 0 ;
6     i =a[0]*0x1000000+a[1]*0x10000+a[2]*0x100+a[3] ;
7     printf("0x%x\n",i) ;
8 }