Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is bitwise & equivalent to modulo operation

Tags:

c

I came across the following snippet which in my opinion is to convert an integer into binary equivalence. Can anyone tell me why an &1 is used instead of %2 ? Many thanks.

for (i = 0; i <= nBits; ++i) {
    bits[i] = ((unsigned long) x & 1) ? 1 : 0;
    x = x / 2;
}
like image 494
B.T Gutsu Avatar asked Dec 12 '22 00:12

B.T Gutsu


1 Answers

The representation of unsigned integers is specified by the Standard: An unsigned integer with n value bits represents numbers in the range [0, 2n), with the usual binary semantics. Therefore, the least significant bit is the remainder of the value of the integer after division by 2.

It is debatable whether it's useful to replace readable mathematics with low-level bit operations; this kind of style was popular in the 70s when compilers weren't very smart. Nowadays I think you can assume that a compiler will know that dividing by two can be realized as bit shift etc., so you can just Write What You Mean.

like image 114
Kerrek SB Avatar answered Jan 02 '23 22:01

Kerrek SB