Clever Use of consortium and location segments

Source: Internet
Author: User

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
  1. Typedef unsigned char uchar;
  2. Uchar * ADDR = (uchar *) 0x10;
  3. If I want to view the value of a bit in the register
  4. (1) uchar value = * ADDR;
  5. (2) perform bitwise operations on the value to view the value of a bit.
  6. If I want to write a value to a bit in the register
  7. Follow these steps:
  8. (1) Value = * ADDR;
  9. (2) modify the value of value through bitwise operation
  10. (3) * ADDR = value; then write the value back to the Register.
  11. Bit operations are troublesome and it is not intuitive to write code.

Until you see such code ~!

 

 

[CPP]View plaincopy
  1. Typedef struct {
  2. Uchar bit0: 1;
  3. Uchar bit1: 1;
  4. Uchar bit2: 1;
  5. Uchar bit3: 1;
  6. Uchar bit4: 1;
  7. Uchar bit5: 1;
  8. Uchar bit6: 1;
  9. Uchar bit7: 1;
  10. } Bits;
  11. Typedef Union {
  12. Uchar data_char;
  13. Bits data_bits;
  14. } Utype;
  15. Uchar * ADDR = (uchar *) 0x10;
  16. Utype value;
  17. Value. data_char = * ADDR;
  18. If you want to view a bit, such as 3rd bits
  19. You can view value. data_bits.bit3 directly.
  20. If you want to set a bit, for example, set 0th bits to 1 and 7th bits to 0
  21. Value. data_bits.bit0 = 1;
  22. Value. data_bits.bit7 = 0;
  23. * ADDR = value. data_char;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.