Why wrap a struct with a union?

Eric Tsui

I saw a code snippet from a good answer for Is it possible to insert three numbers into 2 bytes variable?

For example, I want to store date which contain days, months, years.

  • days -> 31, months -> 12, years -> 99.

I want to store 31, 12, 99 in one variable, and will use shift operators << and >> to manipulate it.

//Quoted: the C code from that answer
    union mydate_struct {
        struct {
            uint16_t day : 5;    // 0 - 31
            uint16_t month : 4;  // 0 - 12
            uint16_t year : 7;   // 0 - 127
        };
        uint16_t date_field;
    };

Now, my question is to why wrap the struct with a union? What are the special benefits besides memory related concern?
PS: I know some typical usage to make sure memory size with union.

Because if it is just to use struct, it seems more direct and simple to use:

   typedef struct {
        uint16_t day : 5;    // 0 - 31
        uint16_t month : 4;  // 0 - 12
        uint16_t year : 7;   // 0 - 127
   } mydate_struct;

Update1:

Some conclusion about benefits to wrap a union here:

  • Can initailize the year, month and day simultaneously

The advantage of using the union is that give union my_datestruct u; you can write u.date_field = 0x3456; and initialize the year, month and day fields simultaneously. It is defined by the implementation what that does, and different implementations could define it differently. There's a modest chance that the year will be 0x56, the month 0x08, and the day 0x06 (aka 86-08-06 — century not clearly defined); there's also a modest chance that the year will be 0x1A, the month 0x02, and the day 0x1A (aka 26-02-26 — century still not clearly defined). People have forgotten Y2K already. ----comment of @Jonathan Leffler

  • You can read/write the whole number at once.(----comment of @StenSoft)
deviantfan

An union means that every part in it will use the same memory, so you can use the first or the second part (which can be completely different things). In your case, it´s either the whole struct or the uint16_t date_field.

In context of the linked question, the writer intended to use it to convert a struct with two byte size to a two byte integer and vice-versa. Assign something to the struct and read the int value from the same memory. But this is not allowed in C++ and may not work (multitude of reasons...). It´s not possible to arbitrarily switch between what part is used.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

STRUCT | incomplete type error for struct/union

분류에서Dev

Why this sql union do not run for me?

분류에서Dev

Why is offsetof(member) equal to sizeof(struct)?

분류에서Dev

C ++ boost :: geometry :: index :: rtree left of .select_on_container_copy_construction must have class / struct / union

분류에서Dev

구조 | struct / union에 대한 불완전한 유형 오류

분류에서Dev

OpenSSL 1.1.0의 EVP_get_cipherbyname 및 "undefined struct / union evp_cipher_st"

분류에서Dev

Why does this python function not work if I wrap it in a def() call?

분류에서Dev

Why does the malloc order matter when a struct is sufficiently sized?

분류에서Dev

Why does xterm/bash word-wrap even tho window is large to fit command

분류에서Dev

VSCode MyPy 오류 : "ioctl"에 호환되지 않는 "my_struct"유형이 있습니다. 예상 "Union [int, str]"

분류에서Dev

'-> NewGlobalRef'의 Left가 struct / union을 가리켜 야하는 의미는 무엇입니까?

분류에서Dev

오류 : 함수에서 struct를 param으로 전달할 때 표현식에는 c에 struct 또는 union 유형이 있어야합니다.

분류에서Dev

String not wrap

분류에서Dev

Why doesn't the packed length of my data correspond to what was declared in the struct?

분류에서Dev

why do I have to declare an irrelevant struct file_handle variable before I can use that type?

분류에서Dev

Union with pointers

분류에서Dev

Struct의 Struct

분류에서Dev

BigQuery-데이터 유형이 다른 UNION ALL 및 STRUCT를 사용하는 동안에는 DISTINCT를 사용할 수 없습니다.

분류에서Dev

프로그램의 메모리 할당에 따라 enum, struct, union, classes, Interface 및 이들 간의 관계가 다른 점

분류에서Dev

struct 및 union 객체에 저장된 값이 패딩 바이트에 해당하는 이유는 지정되지 않은 값을 사용합니까?

분류에서Dev

LinkedList: Why there is need to declare a new struct node current? The code works perfectly fine if I use the argument head for tracking?

분류에서Dev

pacmatic wrap이있어 yay wrap powerpill wrap pacman

분류에서Dev

SQL-UNION, UNION ALL, INTERSECT, EXCEPT

분류에서Dev

FrameLayout wrap_content

분류에서Dev

Wrap and remove extra characters

분류에서Dev

Wrap R function in python

분류에서Dev

Rcpp Class wrap and as

분류에서Dev

Force label line wrap

분류에서Dev

Div to Wrap Content?

Related 관련 기사

  1. 1

    STRUCT | incomplete type error for struct/union

  2. 2

    Why this sql union do not run for me?

  3. 3

    Why is offsetof(member) equal to sizeof(struct)?

  4. 4

    C ++ boost :: geometry :: index :: rtree left of .select_on_container_copy_construction must have class / struct / union

  5. 5

    구조 | struct / union에 대한 불완전한 유형 오류

  6. 6

    OpenSSL 1.1.0의 EVP_get_cipherbyname 및 "undefined struct / union evp_cipher_st"

  7. 7

    Why does this python function not work if I wrap it in a def() call?

  8. 8

    Why does the malloc order matter when a struct is sufficiently sized?

  9. 9

    Why does xterm/bash word-wrap even tho window is large to fit command

  10. 10

    VSCode MyPy 오류 : "ioctl"에 호환되지 않는 "my_struct"유형이 있습니다. 예상 "Union [int, str]"

  11. 11

    '-> NewGlobalRef'의 Left가 struct / union을 가리켜 야하는 의미는 무엇입니까?

  12. 12

    오류 : 함수에서 struct를 param으로 전달할 때 표현식에는 c에 struct 또는 union 유형이 있어야합니다.

  13. 13

    String not wrap

  14. 14

    Why doesn't the packed length of my data correspond to what was declared in the struct?

  15. 15

    why do I have to declare an irrelevant struct file_handle variable before I can use that type?

  16. 16

    Union with pointers

  17. 17

    Struct의 Struct

  18. 18

    BigQuery-데이터 유형이 다른 UNION ALL 및 STRUCT를 사용하는 동안에는 DISTINCT를 사용할 수 없습니다.

  19. 19

    프로그램의 메모리 할당에 따라 enum, struct, union, classes, Interface 및 이들 간의 관계가 다른 점

  20. 20

    struct 및 union 객체에 저장된 값이 패딩 바이트에 해당하는 이유는 지정되지 않은 값을 사용합니까?

  21. 21

    LinkedList: Why there is need to declare a new struct node current? The code works perfectly fine if I use the argument head for tracking?

  22. 22

    pacmatic wrap이있어 yay wrap powerpill wrap pacman

  23. 23

    SQL-UNION, UNION ALL, INTERSECT, EXCEPT

  24. 24

    FrameLayout wrap_content

  25. 25

    Wrap and remove extra characters

  26. 26

    Wrap R function in python

  27. 27

    Rcpp Class wrap and as

  28. 28

    Force label line wrap

  29. 29

    Div to Wrap Content?

뜨겁다태그

보관