 How to get nth bit from number? | Sololearn: Learn to code for FREE!

+3

# How to get nth bit from number?

+10

To get the 3rd bit: n >> 2 shifts the 3rd bit all the way to the right. (n >> 2) & 1 shifts the 3rd bit all the way to the right and then extracts the rightmost bit. In general you want to shift by `i - 1` to get the i-th bit.

+3

Use bitwise & "and" with a mask where the Nth bit of the mask is set to 1.

+3

and what do you say about a way to put this two-bit number in an array (each digit in a separate cell) and access it by the array index? a = [1,0,1,0,1]

+2

Hello! you mean two bit calculus?

+2

+2

Do you index from zero or one? For a binary number, which bit has the lowest index in your idea? is it the left most bit, or the right most one? 10101010 Is bit 1 (left most) or bit 0 (right most) having index 0?

+2

+2

do you understand what Ipang asked you?

+2

do you use bitwise shift to solve this problem?

+2

Reed Richards just the same. according to the same scheme

+1

Please specify a language in your question tags, you have taken multiple courses it is difficult to deduce a context in regards to which language 👍 (Edit) Specified language added in tags. Thank you for understanding 👍

+1

i mean, how to get nth bit from number

+1

do you have any thoughts on how to do this?

+1

I was going to propose this, but Schindlabua's method is way neater 😆 Just as an alternative though, (n & (1 << index) ? 1 : 0) * Where <n> is the number, and <index> is N - 1, so <index> would be 2 if you want to get the 3rd bit.

+1

Third number from right it should be a

+1

NoobTech2.0, similar to what Ipang was saying: You shift a 1 to wherever you need it, and then you binary-or the results. n | (1 << index)

+1

How to get nth bit from number for which language please specify

0

There is number 21 (which is 10101), and i want to get (for example) 3th bit. How i would do it?

0

Yes, I am indexing from the most right one