1

Please, explain why by doing as follows I'll get a second bit of the number stored in i in it's internal representation.

(i & 2) / 2;
japan
  • 137
  • 5

4 Answers4

4
  1. Doing i & 2 masks out all but the second bit in i. [1]
  2. That means the expression evaluates to either 0 or 2 (binary 00 and 10 respectively).
  3. Dividing that by 2 gives either 0 or 1 which is effectively the value of the second bit in i.

For example, if i = 7 i.e. 0111 in binary:

  1. i & 2 gives 0010.
  2. 0010 is 2 in decimal.
  3. 2/2 gives 1 i.e. 0001.

[1] & is the bitwise AND in C. See here for an explanation on how bitwise AND works.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Perhaps your first sentence is a bit convoluted - I would state it as it masks to the the bits of `2` namely to `0000 0010` or something of this sort – DanZimm Mar 05 '15 at 07:18
  • @DanZimm Hmm maybe, edited it now, should be clearer. – Emil Laine Mar 05 '15 at 07:22
  • Ya, I agree, unsure what the issue is with the downvoter, thought it was fine then as well as now. – DanZimm Mar 05 '15 at 07:24
3

i & 2 masks out all but the second bit.

Dividing it by 2 is the same as shifting down 1 bit.

e.g.

i = 01100010
(i & 2) == (i & 00000010) = 00000010
(i & 2) / 2 == (i & 2) >> 1 = 00000001
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
1

The & operator is bitwise AND: for each bit, the result is 1 only if the corresponding bits of both arguments are 1. Since the only 1 bit in the number 2 is the second-lowest bit, a bitwise AND with 2 will force all the other bits to 0. The result of (i & 2) is either 2 if the second bit in i is set, or 0 otherwise.

Dividing by 2 just changes the result to 1 instead of 2 when the second bit of i is set. It isn't necessary if you're just concerned with whether the result is zero or nonzero.

Wyzard
  • 33,849
  • 3
  • 67
  • 87
0

2 is 10 in binary. & is a bitwise conjunction. So, i & 2 gets you the second-from-the-end bit of i. And dividing by 2 is the same as bit-shifting by 1 to the right, which gets the value of the last bit.

Actually, shifting to the right would be better here, as it clearly states your intent. So, this code would be normally written like this: (i & 0x02) >> 1