getbits.c
K&R, p. 49
download
#include <stdio.h> // for printf(), scanf(), putchar()
#define LENGTH 100 // bits
// get the last n bits from x starting at position p:
unsigned getbits(unsigned x, int p, int n);
// reverse s[], knowing its length:
void reverse(char s[], int len);
// get the bits of x into bits[], return length of bits[] (no of bits):
int bitstring (char bits[], unsigned x);
int main()
{
char bits[LENGTH];
unsigned x;
int len, p, n, diff;
printf("Give a positive integer: ");
scanf("%u", &x);
len = bitstring(bits, x);
printf("%s\n", bits);
printf("Return last 0 <= n <= %d bits ", len);
printf("starting at position max(0, n-1) <= p <=%d:\n", len-1);
printf ("n = ");
scanf("%d", &n);
printf ("p = ");
scanf("%d", &p);
x = getbits(x,p,n);
len = bitstring(bits,x);
diff = n - len;
while (diff > 0)
{
putchar('0');
diff--;
}
printf("%s\n", bits);
return 0;
}
// get the last n bits from x starting at position p:
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~0 << n);
}
// reverse s[], knowing its length:
void reverse(char s[], int len)
{
int i = 0, j = len-1;
char temp;
while (i < j)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
// get the bits of x into bits[], return length of bits[] (no of bits):
int bitstring (char bits[], unsigned x)
{
int i = 0;
if (x == 0)
{
bits[i++] = '0';
bits[i] = '\0';
return i;
}
while (x > 0)
{ // last bit gives the parity:
bits[i++] = '0' + x % 2; // 0 for even, 1 for odd
x /= 2; // x = x / 2; // lose last bit
}
bits[i] = '\0'; // end the string
reverse(bits, i);
return i;
}
/*
gcc getbits.c -o getbits
./getbits
Give a positive integer: 74
1001010
Return last 0 <= n <= 7 bits starting at position max(0, n-1) <= p <=6:
n = 3
p = 4
010
./getbits
Give a positive integer: 74
1001010
Return last 0 <= n <= 7 bits starting at position max(0, n-1) <= p <=6:
n = 3
p = 5
001
./getbits
Give a positive integer: 97
1100001
Return last 0 <= n <= 7 bits starting at position max(0, n-1) <= p <=6:
n = 3
p = 4
000
./getbits
Give a positive integer: 97
1100001
Return last 0 <= n <= 7 bits starting at position max(0, n-1) <= p <=6:
n = 4
p = 3
0001
./getbits
Give a positive integer: 97
1100001
Return last 0 <= n <= 7 bits starting at position max(0, n-1) <= p <=6:
n = 5
p = 5
10000
*/
Comments
Post a Comment