fork download
  1. #include<stdio.h>
  2.  
  3. unsigned getbits(unsigned x, int p, int n)
  4. {
  5. /* Build a mask consisting of 'n' bits */
  6. /* ...111 */
  7. int all_ones = ~0;
  8. /* ...111000 */
  9. int all_ones_shifted_left = all_ones << n;
  10. /* ...000111 */
  11. int mask = ~all_ones_shifted_left;
  12.  
  13. /* Shift 'x' down to discard lower bits we don't care about */
  14. /* How many bits do we discard? */
  15. int shift_down = p + 1 - n;
  16. /* ...76543210 -> ...765432 */
  17. unsigned int x_shifted_down = x >> shift_down;
  18.  
  19. /* Use the mask to discard the upper bits we don't care about */
  20. return x_shifted_down & mask;
  21. }
  22.  
  23. int main(void)
  24. {
  25. /* Decimal 8 is binary 1000 */
  26. unsigned x = 8;
  27. /* Position 4 starts at ...[43210 */
  28. int p = 4;
  29. /* 3 bits means the range is ...[432]10 */
  30. int n = 3;
  31.  
  32. printf("%d", getbits(x, p, n));
  33. return 0;
  34. }
Success #stdin #stdout 0.01s 1720KB
stdin
Standard input is empty
stdout
2