Hi all, I have just started on the low level programming chapter in KNKING C programming book, and am confused by this exercise. This is what it does.
(a) Write the following function
intcount_ones(unsignedchar ch);
count_ones should return the number of 1 bits in ch.
This is what I came up with (and apparently is correct as i cross checked with online answers)
Code:
int count_ones_v1(unsigned char ch)
{
short count;
while (ch > 0) {
if (ch & 1) {
count++;
}
ch >>= 1;
}
}
From my understanding, what my code does is it uses & to check if the right most bit of ch contains a 1. If it does, then it adds to the "count" variable. It then uses >> to move ch to the right, and repeats until ch ==0 and the loop is broken.
The 2nd part of the exercise goes "Write the function without using a loop" and this is what the online answer has shown.
Code:
int count_ones(unsigned char ch)
Code:
{
if (ch == 0)
return 0;
return count_ones(ch & ch - 1) + 1;
}
I understand that this function is recursive, but I dont understand how (ch & ch - 1) works, and why afterwards there is an additonal "+1". Isnt "ch-1" basically just subtracting a decimal value of 1 from ch? Would appreciate any help and guidance.
Also is it expected to be able to convert decimal numbers to hexadecimal form with ease? Trying to convert hex values to decimal makes me feel dumb haha. Thank you kind sirs.