简体   繁体   中英

Is bitwise & equivalent to modulo operation

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;
}

The representation of unsigned integers is specified by the Standard: An unsigned integer with n value bits represents numbers in the range [0, 2 n ), 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.

what the code snippet does, is not to convert a unsigned int into a binary number (it's internal representation is already binary). It created a bit array with the values of the unsigned int's bits. Spreads it out over an array if you will.

e.g. x=3  =>  bits[2]=0 bits[1]=1 bits[0]=1

To do this

  1. it selects the last bit of the number and places it the bits array (the &1 operation).
  2. then shifts the number to the right by one position ( /2 is equivalent to >>1).
  3. Repeats the above operations for all the bits

You could have used %2 instead of &1, the generated code should be the same. But I guess it's just a matter of programming style and preference. For most programmers, the &1 is a lot clearer than %2.

In your example, %2 and &1 are the same. Which one to take is probably simply a matter of taste. While %2 is probably more easier to read for people with a strong mathematics background, &1 is easier to understand for people with a strong technical background.

They are equivalent in the very special case. It's an old Fortran influenced style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM