Skip to content

Little experiment to check how integer promotion affects bitfields

License

Notifications You must be signed in to change notification settings

Marcondiro/c_bitfields_integer_promotion

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

c_bitfields_integer_promotion

Little experiment to check how integer promotion affects bitfields.

The interest in this came after the discussion at https://lore.kernel.org/all/6ab8c7fd-c718-49ff-bbbb-9241293127f7@intel.com/t/#u

Turns out that for bitfields bigger than sizeof(int) the behavior is compiler dependent.

#include <stdio.h>
struct s1{
unsigned int a: 20;
unsigned int _: 12;
};
struct s2 {
unsigned long long b: 40;
unsigned long long _: 24;
};
int main()
{
struct s1 s1;
struct s2 s2;
s1.a = 2;
s2.b = 2;
unsigned int a = s1.a << 19;
unsigned long long b = s2.b << 39;
printf("0x%x\n", a); //both gcc and clang: 0x100000
printf("0x%llx\n", b); //gcc: 0x0 clang: 0x10000000000
return 0;
}
/*
Debian clang version 18.1.8
gcc (Debian 12.2.0-14) 12.2.0
*/

A bunch of related links

https://gcc.gnu.org/onlinedocs/gcc/Structures-unions-enumerations-and-bit-fields-implementation.html

https://stackoverflow.com/questions/2647320/struct-bitfield-max-size-c99-c

https://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#Bit-Fields

https://archive.org/details/the-ansi-c-programming-language-by-brian-w.-kernighan-dennis-m.-ritchie.org/page/132/mode/2up

https://stackoverflow.com/questions/32529080/should-bit-fields-less-than-int-in-size-be-the-subject-of-integral-promotion

https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules

https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2310.pdf

About

Little experiment to check how integer promotion affects bitfields

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages