When I was a beginner at the C-language union, I was always wondering where to use it. Even a year before my work, I basically thought union was useless until I saw a lot of code written by cool, I am deeply impressed with the endless learning experience!
For more information about the code, see the following application scenarios:
In hardware programming, bitwise operations are often performed, assuming that the Register is 8 bits (here it is a bit too lazy to write 32 bits ), and the address of a register is 0x10. Now I want to read and write the register.
[CPP]View plaincopy
- Typedef unsigned char uchar;
- Uchar * ADDR = (uchar *) 0x10;
- If I want to view the value of a bit in the register
- (1) uchar value = * ADDR;
- (2) perform bitwise operations on the value to view the value of a bit.
- If I want to write a value to a bit in the register
- Follow these steps:
- (1) Value = * ADDR;
- (2) modify the value of value through bitwise operation
- (3) * ADDR = value; then write the value back to the Register.
- Bit operations are troublesome and it is not intuitive to write code.
Until you see such code ~!
[CPP]View plaincopy
- Typedef struct {
- Uchar bit0: 1;
- Uchar bit1: 1;
- Uchar bit2: 1;
- Uchar bit3: 1;
- Uchar bit4: 1;
- Uchar bit5: 1;
- Uchar bit6: 1;
- Uchar bit7: 1;
- } Bits;
- Typedef Union {
- Uchar data_char;
- Bits data_bits;
- } Utype;
- Uchar * ADDR = (uchar *) 0x10;
- Utype value;
- Value. data_char = * ADDR;
- If you want to view a bit, such as 3rd bits
- You can view value. data_bits.bit3 directly.
- If you want to set a bit, for example, set 0th bits to 1 and 7th bits to 0
- Value. data_bits.bit0 = 1;
- Value. data_bits.bit7 = 0;
- * ADDR = value. data_char;