Is there a bit-equivalent of sizeof() in C? -


sizeof() doesn't work when applied 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 bit-field 

...obviously, since can't return floating point partial size or something. however, brought interesting question. is there equivalent, in c, tell number of bits in variable/type? ideally, work regular types well, char , int, in addition bitfields.

update:

if there's no language equivalent of sizeof() bitfields, efficient way of calculating - @ runtime! imagine have loops depend on this, , don't want them break if change size of bitfield - , no fair cheating , making bitfield size , loop length macro. ;-)

you cannot determine size of bit-fields in c. can, however, find out size in bits of other types using value of char_bit, found in limits.h. size in bits char_bit * sizeof (type).

do not assume c byte octet, at least 8 bit. there actual machines 16 or 32 bit bytes.

concerning edit: bit-field int a: n; has size of n bits definition. padding bits when put in struct belong struct , not bit-field.

my advice: don't use bit-fields use (arrays of) unsigned char , work bitmasks. way lot of behaviour (overflow, no padding) defined.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -