union的实际使用
记录一下,免得忘记:
1、定义一个共用体变量
这里定义一个64位变量 i2creg_rev,然后通过共用体定义两个位变量bits和bits_reverse,通过bit可以访问指定位的值大小,不需要自己再左移右移转换。
bits_reverse是bits的对端转换,是用来处理大小端定义位的,免得取位值时,取反顺序了
typedef union
{
unsigned long long int i2creg_rev; /**< the whole byte */
struct
{
u64 sec : 6; /**< binary sec :7bit */
u64 min : 6; /**< binary min */
u64 hour : 5; /**< binary hour */
u64 tod_daysL : 9; /**< binary day */
u64 year : 7;
u64 tod_secs : 17; /**< binary day-secs */
u64 rev :14;
} bits;
struct
{
u64 rev :14;
u64 tod_secs : 17; /**< binary day-secs */
u64 year : 7;
u64 tod_daysL : 9; /**< binary day */
u64 hour : 5; /**< binary hour */
u64 min : 6; /**< binary min */
u64 sec : 6; /**< binary sec :7bit */
} bits_reverse;
} irigb_i2creg_rev;
2、使用
先定义一个union变量,然后用i2c去读的值,赋值给rev_time,之后利用union特性,直接可以提取时分秒,年月日了
void test_union(void)
{
irigb_i2creg_rev rev_time;
unsigned char tdata[20] = { 0 };
interface_phasei2c_read_nbytes(0x90, 0xC8, tdata, 8);
Str_Printf("r 0xC8=0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x \t",
tdata[7],tdata[6],tdata[5],tdata[4],tdata[3],tdata[2],tdata[1],tdata[0]);
rev_time.i2creg_rev = ((unsigned long long int)tdata[0]<<56 | (unsigned long long int)tdata[1]<<48 | (unsigned long long int)tdata[2]<<40 |(unsigned long long int)tdata[3]<<32 |
(unsigned long long int)tdata[4]<<24 |(unsigned long long int)tdata[5]<<16 |(unsigned long long int)tdata[6]<<8 |(unsigned long long int)tdata[7]
);
Str_Printf("%d:%d:%d,%d,%d,@%d\r\n",rev_time.bits.hour, rev_time.bits.min, rev_time.bits.sec,
rev_time.bits.tod_daysL, rev_time.bits.year+2000, rev_time.bits.tod_secs);
// Str_Printf("%d:%d:%d,%d,%d,@%d\r\n",rev_time.bits_reverse.hour, rev_time.bits_reverse.min, rev_time.bits_reverse.sec,
// rev_time.bits_reverse.tod_daysL, rev_time.bits_reverse.year+2000, rev_time.bits_reverse.tod_secs);
}