强制转换的研究(2)

/***************************************************
 *作     者:温子祺
 *联系方式:wenziqi@hotmail.com
 *说    明 :强制转换的研究-(2) 
 ***************************************************/

 

代码
例子4:在大端模式下(8051系列单片机是大端模式)将含有位域的结构体赋给无符号字节整型值

方法1:逐位赋值。

typedef
struct __BYTE2BITS

{

UINT8 _bit7:
1;

UINT8 _bit6:
1;

UINT8 _bit5:
1;

UINT8 _bit4:
1;

UINT8 _bit3:
1;

UINT8 _bit2:
1;

UINT8 _bit1:
1;

UINT8 _bit0:
1;

}BYTE2BITS;



BYTE2BITS Byte2Bits;



Byte2Bits._bit7
=0;

Byte2Bits._bit6
=0;

Byte2Bits._bit5
=1;

Byte2Bits._bit4
=1;

Byte2Bits._bit3
=1;

Byte2Bits._bit2
=1;

Byte2Bits._bit1
=0;

Byte2Bits._bit0
=0;



UINT8 a
=0;



a
|= Byte2Bits._bit7<<7;

a
|= Byte2Bits._bit6<<6;

a
|= Byte2Bits._bit5<<5;

a
|= Byte2Bits._bit4<<4;

a
|= Byte2Bits._bit3<<3;

a
|= Byte2Bits._bit2<<2;

a
|= Byte2Bits._bit1<<1;

a
|= Byte2Bits._bit0<<0;



结果:a
=0x3C



方法2:强制转换。

typedef
struct __BYTE2BITS

{

UINT8 _bit7:
1;

UINT8 _bit6:
1;

UINT8 _bit5:
1;

UINT8 _bit4:
1;

UINT8 _bit3:
1;

UINT8 _bit2:
1;

UINT8 _bit1:
1;

UINT8 _bit0:
1;

}BYTE2BITS;



BYTE2BITS Byte2Bits;



Byte2Bits._bit7
=0;

Byte2Bits._bit6
=0;

Byte2Bits._bit5
=1;

Byte2Bits._bit4
=1;

Byte2Bits._bit3
=1;

Byte2Bits._bit2
=1;

Byte2Bits._bit1
=0;

Byte2Bits._bit0
=0;



UINT8 a
=0;



a
= *(UINT8 *)&Byte2Bits



结果:a
=0x3C


例子5:在大端模式下(8051系列单片机是大端模式)将无符号字节整型值赋给含有位域的结构体。

方法1:逐位赋值。

typedef
struct __BYTE2BITS

{

UINT8 _bit7:
1;

UINT8 _bit6:
1;

UINT8 _bit5:
1;

UINT8 _bit4:
1;

UINT8 _bit3:
1;

UINT8 _bit2:
1;

UINT8 _bit1:
1;

UINT8 _bit0:
1;

}BYTE2BITS;



BYTE2BITS Byte2Bits;



UINT8 a
=0x3C;



Byte2Bits._bit7
=a&0x80;

Byte2Bits._bit6
=a&0x40;

Byte2Bits._bit5
=a&0x20;

Byte2Bits._bit4
=a&0x10;

Byte2Bits._bit3
=a&0x08;

Byte2Bits._bit2
=a&0x04;

Byte2Bits._bit1
=a&0x02;

Byte2Bits._bit0
=a&0x01;

方法2:强制转换。

typedef
struct __BYTE2BITS

{

UINT8 _bit7:
1;

UINT8 _bit6:
1;

UINT8 _bit5:
1;

UINT8 _bit4:
1;

UINT8 _bit3:
1;

UINT8 _bit2:
1;

UINT8 _bit1:
1;

UINT8 _bit0:
1;

}BYTE2BITS;



BYTE2BITS Byte2Bits;



UINT8 a
=0x3C;



Byte2Bits
= *(BYTE2BITS *)&a;
原文地址:https://www.cnblogs.com/wenziqi/p/1769381.html