Bit of This AND That?


#1

So, I understand how to read bits.

0b1 = 1
0b10 = 2
0b100 = 4
etc.

What I don't understand is how 0b111 & 0b1010 = 0b10.

See, when I looked at the tutorial, I figured it would be like this.

0b111
0b1010
======
0b101

Because 1 & 1 = 1 and anything else turns the value into 0. Can someone explain this to me? Am I simply lining up the values wrong? Like, should I translate 0b111 to 0b0111 to make sure things line up well because that 0 at the end has no pair?

0b0111
0b1010
======
0b0010 which then equals to 0b10 which is supposedly the correct answer?

I just want to make sure that I'm doing this correctly from the beginning. Thank you guys in advance!


#2

When you are reading bits you are starting from right to left.
If you have number with 8 bits 1 is represented like 0000 0001 - with 7 zero bits on the left.
If you have number with 16 bits: 1 is 0000 0000 0000 0001 - with 15 zero bits.
etc.

When you and bits:
0 and 0 = 0
0 and 1 = 0
1 and 0 = 0
1 and 1 = 1

Only 1 and 1 is equal to 1.

In your case this is the right solution:


#3

Hello, my answer :>> print bin(14 & 5)


#4

But I can understand it isn't the right way ...


#5

that what they saying in the excises :

0b111 (7) & 0b1010 (10) = 0b10

so who can be the result = 0b10
i think it must be

0b010