Advertisement
SepandMeenu

Bit manipulation

Jan 15th, 2025
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.71 KB | Source Code | 0 0
  1. #include <stdio.h>
  2.  
  3. typedef void (*bit_fn_t)(const int, const int);
  4.  
  5. // extract and transform bits
  6. void transform_bits(bit_fn_t bit_fn, unsigned int x, int n) {
  7.     for (int idx = n - 1; idx >= 0; --idx) {
  8.         const int bit = (x >> idx) & 1;
  9.         bit_fn(idx, bit);
  10.     }
  11. }
  12.  
  13. // function to apply to each bit
  14. void bitFoo(const int bit_idx, const int bit) {
  15.     printf("%d) %d\n", bit_idx, bit);
  16. }
  17.  
  18. int main() {
  19.     unsigned int x = 103;  // = '01100111'
  20.     int n = 8;  // number of bits to extract
  21.  
  22.     printf("> bits of %u:\n", x);
  23.     transform_bits(bitFoo, x, n);
  24.     printf("\n");
  25.  
  26.     return 0;
  27. }
  28.  
  29. //** compile:
  30. // gcc -std=c11 -Wall -O3 -o bits.exe bits.c
  31.  
  32. //** run:
  33. // ./bits.exe
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement