I am working on a problem, which asked for a program to view and set different bits of a number. Here is what I have. Can this be improved in any way? I already know about the bit fields; the author asked to do it this way.
Code:
#include <stdio.h>
unsigned int bit_test( unsigned int value, int n)
{
//value <<= n;
value = (value >> n) & 0x01;
return value;
}
unsigned bit_set ( unsigned int value, int n)
{
value |= 1 << n;
return value;
}
void show_bits(unsigned int value)
{
int i;
for (i=0; i<32; i++) // Create a sepaate function for this
{
bit_test(value, i);
printf ("The value of bit #%d for the number %d is:%d\n", i, value,bit_test(value, i));
}
}
int main (void)
{
unsigned int value;
int i, n;
n =3;
value = 5577;
for (i=0; i<32; i++) // Create a sepaate function for this
{
bit_test(value, i);
printf ("The value of bit #%d for the number %d is:%d\n", i, value,bit_test(value, i));
}
printf("\nIf you want to set one of the bits of value, type in the bit number (0 - 31)");
scanf("%d",&n);
value = bit_set (value, n);
show_bits(value);
}