Hello,
I'm working on Practical C Programming exercise 11-6 and have a solution. I just feel like it's kind of messy, so I wanted to see if others had feedback on a cleaner, easier way. Mind you, we haven't reach pointers yet in the book. Thanks!
Code:
/*************************************************************
pcp11_6 -- Takes the 1 bits in a number and shifts them to the left
end.
*************************************************************/
#include <stdio.h>
char line[100]; /* user input */
unsigned char num; /* number from user input (8-bit)*/
int ones_count; /* number of 1s to shift */
unsigned char new_num; /* new number with shifted bits */
int i,j; /* counters */
int k; /* bit shift counter */
int main(void)
{
//initialize vars
ones_count = 0;
k = 7;
// Get user input and store in integer
printf("Please enter a number (1 to 255): ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &num);
// Count number of 1s in the 8-bit number
for(i = 0x80; i > 0; i = (i >> 1))
{
if(num & i)
{
++ones_count;
}
}
// Create new number, bit-by-bit
for(i = 0x80; i > 0; i = (i >> 1))
{
// Push all of the 1s to the left side of the new number
while(ones_count != 0)
{
new_num |= 1 << k;
i = i >> 1;
--ones_count;
--k;
}
// Fill in the rest of the number with 0s
new_num |= 0 << k;
--k;
}
printf("\nNew number is = %d.\n", new_num);
return 0;
}