Advertisement
STANAANDREY

k&r 2-6

Oct 28th, 2022
1,065
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.67 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. unsigned setbits(unsigned x, unsigned p, unsigned n, unsigned y) {
  4.   unsigned mask = (1 << n) - 1;
  5.   unsigned rmy = mask & y;
  6.   return (x & (~mask << (p - n + 1))) | rmy;
  7. }
  8.  
  9. void showBits(unsigned a){
  10.     for(int i = sizeof(a) * 8 - 1; i>= 0; i--)
  11.         printf("%d", ( a >> i) & 1);
  12.     printf("\n");
  13. }
  14.  
  15. unsigned read(char ch) {
  16.   unsigned nr;
  17.   printf("%c=", ch); scanf("%u", &nr);
  18.   return nr;
  19. }
  20.  
  21. int main() {
  22.   unsigned x, p, n, y;
  23.   x = read('x'), p = read('p'), n = read('n'), y = read('y');
  24.  
  25.   showBits(x);
  26.   showBits(y);
  27.  
  28.   unsigned ans = setbits(x, p, n, y);
  29.   //printf("%u\n", ans);
  30.   showBits(ans);
  31.  
  32.   return 0;
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement