Advertisement
BenTibnam

Bit manipulation through unions

Nov 21st, 2023 (edited)
499
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.86 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. typedef struct {
  4.     unsigned b0: 8, b1: 8, b2: 8, b3: 8;
  5. } word_bytes;
  6.  
  7. typedef struct{
  8.     unsigned b0: 1, b1: 1, b2: 1, b3: 1, b4: 1, b5: 1, b6: 1, b7: 1, b8: 1, b9: 1, b10: 1, b11: 1, b12: 1, b13: 1, b14: 1, b: 15, b16: 1, b17: 1, b18: 1, b19: 1, b20: 1, b21: 1, b22: 1, b23: 1, b24: 1, b25: 1, b26: 1, b27: 1, b28: 1, b29: 1, b30: 1, b31: 1;
  9. } word_bits;
  10.  
  11. typedef union {
  12.     int         i;
  13.     word_bits   bit;
  14.     word_bytes  bytes;
  15. } word;
  16.  
  17. int main()
  18. {
  19.     // sets all bits to 0
  20.     word w = {0};
  21.    
  22.     // turing on bits
  23.     w.bit.b8 = 1;
  24.     w.bit.b12 = 1;
  25.    
  26.     // first 8 bits
  27.     w.bytes.b0 = 'a';
  28.    
  29.     // third 8 bits
  30.     w.bytes.b2 = 'A';
  31.    
  32.     // fourth 8 bits
  33.     w.bytes.b3 = 12;
  34.    
  35.     printf("w.i = %d\n", w.i);
  36.     printf("w.b2 = %d  %c\n", w.bytes.b2, w.bytes.b2);
  37.     return 0;  
  38. }
Tags: Bits unions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement