+ 10
How to calculate size of data types in C?
See the below Code. It's a challenge question and size is coming 8. How? Anyone please can explain? #include <studio.h> typedef struct { int bit1 : 1; int bit2 : 2; int bit30 : 30; } bits; int main() { printf("%d", sizeof(bits)); return 0; } output : 8
10 Respostas
+ 15
int bit1:1; --> 'int' indicates that it is a SIGNED integer.
For signed integers the leftmost bit will be taken for +/- sign.
If you store 1 in 1-bit field:
The left most bit is 1, so the system will treat the value as negative number.
The 2's complement method is used by the system to handle the negative values.
Therefore, the data stored is 1. The 2's complement of 1 is also 1 (negative).
Now in the q all 3 declarations are there
=> Bit1:1
Binary is 1
2's compliment is 0
So,1 bit
=>Bit2:2
Binary is 10
2's compliment is 01
So,2 bits
=>Bit30:30
Binary is 11110
2s compliment is 00001
So,5bits
So 1+2+5=8
Sizeof() will be a bit representation
+ 13
The struct contains bit fields (reference -> https://en.cppreference.com/w/cpp/language/bit_field).
The type for the members here are `int`, which is (commonly) a 32bit integer. But if we sum the total of bits set, we get 33 (1 + 2 + 30).
For that reason, compiler allocates 8 bytes (64bits) memory for each struct instance. Because allocating 4 bytes (32bits) is not enough to contain all the bits needed by the struct members.
Hth, cmiiw
+ 6
Use sizeof operator it can be applied to structures as well 🙄
+ 6
Sanjay Kamath sizeof() is already being used in the program.
+ 5
Interesting question to Learn a new concept...
33bits with rounded up to 64bits for storage
Thanks for this....
https://www.tutorialspoint.com/cprogramming/c_bit_fields.htm
+ 5
Alaska , colons are needed when defining a bit field.
+ 4
Sonic Ohh, never learned about this bit thing. Thanks, I will check it today.
+ 3
what is that colon for? As far as I have learned, struct variables cannot be initialized at declaration. If those colons and values are removed then works fine.