Sizeof() doesn't work when applied to bitfields:
# cat p.c #include<stdio.h> int main( int argc, char **argv ) { struct { unsigned int bitfield : 3; } s; fprintf( stdout, "size=%d\n", sizeof(s.bitfield) ); } # gcc p.c -o p p.c: In function ‘main’: p.c:5: error: ‘sizeof’ applied to a bit-field
...obviously, since it can't return a floating point partial size or something. However, it brought up an interesting question. Is there an equivalent, in C, that will tell you the number of bits in a variable/type? Ideally, it would also work for regular types as well, like char and int, in addition to bitfields.
Update:
If there's no language equivalent of sizeof() for bitfields, what is the most efficient way of calculating it - at runtime! Imagine you have loops that depend on this, and you don't want them to break if you change the size of the bitfield - and no fair cheating and making the bitfield size and the loop length a macro. ;-)
Answer: sizeof returns the size of the type in bytes. Example: sizeof(char) is 100% guaranteed to be 1 , but this does not mean, that it's one octet (8 bits).
You cannot determine the size of bit-fields in C. You can, however, find out the size in bits of other types by using the value of CHAR_BIT , found in <limits. h> . The size in bits is simply CHAR_BIT * sizeof(type) .
So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.
The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.
You cannot determine the size of bit-fields in C. You can, however, find out the size in bits of other types by using the value of CHAR_BIT
, found in <limits.h>
. The size in bits is simply CHAR_BIT * sizeof(type)
.
Do not assume that a C byte is an octet, it is at least 8 bit. There are actual machines with 16 or even 32 bit bytes.
Concerning your edit: I would say a bit-field int a: n;
has a size of n bits by definition. The extra padding bits when put in a struct belong to the struct and not to the bit-field.
My advice: Don't use bit-fields but use (arrays of) unsigned char
and work with bitmasks. That way a lot of behaviour (overflow, no padding) is well defined.
It is impossible to find a size of bit-field using sizeof(). Refer to C99:
6.5.3.4 The sizeof operator
, bit-field is clearly not supported by sizeof()6.7.2.1 Structure and union specifiers
here it is clarified that bit-field isn't self standing member.Otherwise, you can try to assign to the bit-field member -1u (value with all bits set) and then find the index of the most significant bit. E.g. (untested):
s.bitfield = -1u; num_bits = ffs(s.bitfield+1)-1;
man ffs
for more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With