16进制数据拆分

转:8位16位32位数据的拆分与合并程序

https://blog.csdn.net/qq_31811537/article/details/71760334

 

拆分

//16位拆成两个8位

u16 data16 = 0x1234;

u8 data8_H,data8_L;

data8_H = (u8)(data16 >> 8);

data8_L = (u8)data16;

32位拆成4个8位

方法一:

u32 data32 = 0x12345678;

u8 data8_1,data8_2,data8_3,data8_4;

data8_1 = (u8)(data32 >> 24);

data8_2 = (u8)(data32 >> 16);

data8_3 = (u8)(data32 >> 8);

data8_4 = (u8)data32;

方法二:

u32 data32 = 0x12345678;

u8 data8_1,data8_2,data8_3,data8_4;

u8 *pa; //定义指针

pa = (u8 *)(&data32); //将32位地址,强制转换为8位地址

data8_1 = ((char )pa+3);

data8_2 = ((char )pa+2);

data8_3 = ((char )pa+1);

data8_4 = ((char )pa);

合并

2个8位合并成1个16位

u8 data8_H = 0x12;

u8 data8_L = 0x34;

u16 data16;

data16 = ((u16)data8_H << 8) | (u16)(data8_L));

4个8位合并成1个32位

u8 data8_1 = 0x12;

u8 data8_2 = 0x34;

u8 data8_3 = 0x56;

u8 data8_4 = 0x78;

u32 data32;

data32 = ((u32)data8_1 << 24) | ((u32)data8_2 << 16) | ((u32)data8_3 << 8) | ((u32)data8_4);

 

 

 

 

也可以%:取余

16进制的0x123456 % 0x100 结果等于 0x56, 这点与十进制是一样的。

商为0x1234,

再对0x1234%0x100,结果等于0x34,

商为0x12,

再对0x12%0x100,结果为0x12.

 

quint32 dataValue = 0x123456;


        quint16  dataA = dataValue/0x100;
        quint8 data1=  dataValue % 0x100;

        quint16  dataB = dataA/0x100;
        quint8 data2 = dataA%0x100;

        quint16  dataC = dataB/0x100;
        quint8 data3 = dataB%0x100;
posted @ 2021-10-14 20:42  伟大的厨师  阅读(1208)  评论(0编辑  收藏  举报