aboutsummaryrefslogtreecommitdiff
path: root/2.8.c
blob: 8f3ecbf44ad04c7d4d7107e24ee7b43001ba55a3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdio.h>

#define INT_NBITS 32
#define ONE 1

unsigned getbits(unsigned x, int from, int to);
void pbits(int x);
unsigned rightrot(unsigned x, int n);

int 
main(void)
{
  int x = 2394234;

  pbits(x);

  pbits(rightrot(x, 8));
  
  return 0;
}

unsigned 
getbits(unsigned x, int from, int to)
{
  return (x >> (from+1-to)) & ~(~(unsigned)0 << to);
}

void 
pbits(int x)
{
  for (int i = INT_NBITS-1; i >= 0; i--) {
    if (i%4 == 3)
      printf(" ");

    printf("%u", getbits(x, i, 1));
  }

  printf("\n");
}

unsigned 
rightrot(unsigned x, int n)
{
  int model = (x >> n) << n;
  for (int i = 1; i <= n; i++) {
    int shift = n+1-i*2;

    if (shift >= 0)
      model |= ((x & (ONE << (n-i))) >> shift);
    else
      model |= ((x & (ONE << (n-i))) << -shift);
  }

  return model;
}