Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.
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.
View: https://www.youtube.com/watch?v=NLKQEOgBAnw&t=443s

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?
 
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)
 
To rephrase it:
1) the operator & is doing the logic "and" operation between every single bit of its left-hand operand x and its right-hand operand (1<<i).
2) 1<<i takes the value 1 and shift it i times to the left. The result is a number with all bits at 0 except the ith which is 1.
So the result is either 0 (if the ith bit of x is 0) or i<<i (if the ith bit of x is 1)
This means you could replace
(x&(1<<i)) != 0
by
(x&(1<<i)) == (1<<i)
but the first expression is easier to read (and needs less processing time).
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom