How to determine how many bytes are required for memory allocation for a variable, for example, in a structure, to save memory?

Example:

//без задания размера struct DATETIME { usigned short Year; usigned short Month; usigned short Date; } //с заданием размера struct DATETIME { usigned short Year : 7; //значения меняются от 0 до 99 usigned short Month : 4; //значения меняются от 0 до 12 usigned short Date : 5; //значения меняются от 0 до 31 } 
  • Do you want to know the size of the field on the go or do you want to figure out how to get the size itself? - cy6erGn0m

2 answers 2

What you use in the "with the task of the size" clause is bit fields. Those. You can make variables that will be the size of a multiple byte. As a result, the compiler compiles them. Count the number of bits you need to select easily. We remember that a bit can have 2 values, two bits - 4, etc. by powers of two. Those. we need to take the binary logarithm from the count of values ​​and round to a larger integer. Example: 32 values ​​-> 32 = 2 ^ 5. Total - we need 5 bits to represent 32 different values ​​(ranging from 0 to 31).

    Bitfields .-. Do not save on matches, it will be better.

    If you need 7 bits - so take one-byte type. The closest multiple is 8. The minimum size in bits is determined by the number of possible values ​​for this field. Binary logarithm of quantity.

    The location of the structure fields will also affect its size - there is such a thing as alignment. Although it is all customizable.