fork download
  1. #include <stdio.h>
  2. #include <limits.h>
  3.  
  4. #if CHAR_BIT != 8
  5. #error "unsupported char size"
  6. #endif
  7.  
  8. typedef enum { ONE, TWO, THREE } my_enum;
  9.  
  10. typedef struct
  11. {
  12. unsigned long var1 : 8;
  13. unsigned long var2 : 24;
  14. my_enum var3 : 2;
  15. my_enum var4 : 2;
  16. } my_struct;
  17.  
  18. int main(void)
  19. {
  20. int idx;
  21. int bitIdx;
  22. my_struct my_struct_var;
  23.  
  24. memset (&my_struct_var,
  25. 0,
  26. sizeof(my_struct_var));
  27.  
  28. printf("sizeof(my_struct) = %lu\n", sizeof(my_struct));
  29. printf("sizeof(my_struct_var) = %lu\n", sizeof(my_struct_var));
  30.  
  31. my_struct_var.var1 = 0x81; /* 1000 0001 */
  32. my_struct_var.var2 = 0x800001; /* 1000 0000 0000 0000 0000 0001 */
  33. my_struct_var.var3 = 0b10; /* 10 */
  34. my_struct_var.var4 = 0b11; /* 11 */
  35.  
  36. for (idx = 0; idx < sizeof(my_struct_var); ++idx)
  37. {
  38. char * curByte = &my_struct_var;
  39. curByte += idx;
  40. printf("\nByte %d: ", idx);
  41. for (bitIdx = 0; bitIdx < CHAR_BIT; ++bitIdx)
  42. {
  43. printf("%c ", ((*curByte & (1 << ((CHAR_BIT - 1) - bitIdx))) >> ((CHAR_BIT - 1) - bitIdx)) + '0');
  44. }
  45. }
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
sizeof(my_struct)     = 8
sizeof(my_struct_var) = 8

Byte 0:  1 0 0 0 0 0 0 1 
Byte 1:  0 0 0 0 0 0 0 1 
Byte 2:  0 0 0 0 0 0 0 0 
Byte 3:  1 0 0 0 0 0 0 0 
Byte 4:  0 0 0 0 1 1 1 0 
Byte 5:  0 0 0 0 0 0 0 0 
Byte 6:  0 0 0 0 0 0 0 0 
Byte 7:  0 0 0 0 0 0 0 0