Whereas the first function loops through the given number, checking one bit at a time, the second checks groups of four bits – so it will run four times fewer iterations of its loop (in theory, at least†) than the first does.
It works by 'masking' the number against the value 15
, which, in hexadecimal is 0xF
and in binary is 0b1111
; thus, on each loop, the expression, i&15
(used as the array index) extracts the number represented by lowest four bits; the array, chs
is a pre-defined list of how many bits are set in each of the possible values of that extracted number: the appropriate value is added to the running total, then the bits in the number are shifted down by 4 places (the i >>= 4
operation).
† I say, "in theory," because many compilers will be able to optimize the code generated for either or both of your functions/loops, so predicting which will be the most efficient is not a trivial matter.
Further, the number of loops required before the test number is reduced to zero will be heavily dependent on the initial value of that number so, if your test numbers are biased towards low values, then the reduction of the loop count will become less significant.