Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

John Weiss

Coder
I'm trying to understand the code here
To view this content we will need your consent to set third party cookies.
For more detailed information, see our cookies page.

I don't understand this notation:
` (x&(1<<i)) != 0`

I understand we want to AND the bit at i position with 1, and see if it's equal to 1. So i assume that's what the formula is doing. Is this C code?
`&` must mean `AND`
`i` must be the position, 6 in the example: `(x&(1 << 6)) != 0`. Correct?
What's `x`?
What's `<<`? Does it mean "get the digit at position i"?
Why don't we say `= 1` instead of `!= 0`?

Okay, x is probably a variable, & means logical and so x logical and thing in parentheses, << is bit shift, 1 bit shifted i places, != means not equal, so left side not equal to 0. X E.

Okay, x is probably a variable, & means logical and so x logical and thing in parentheses, << is bit shift, 1 bit shifted i places, != means not equal, so left side not equal to 0. X E.
i think you're right, << is bit shift.
So x must be the byte we're evaluating.
I don't get why we say `!=0` instead of `=1`.

It’s testing the ith bit. Returns true if the ith bit is 1

Eg suppose x is 00001000 and I is 3
The 1 is 00000001
1<<3 is 00001000
X is. 00001000
AND is 00001000. Which is != 0, so the result is. True

Now suppose I = 2
1<<2 is 00000100
X is. 00001000
AND is 00000000. Which is not != 0, so the result is. False

(Examples show x as a byte, but it’s probably an int with a lot more leading 0 bits - doesn’t change the logic)