-2

In doing a bitwise &, I thought by specifying the digit it would add that digit in the necessary spot, but in python I get the following:

>>> 4&2
0

>>> 4&1<<1
0

>>> 0b100 & 0b010
0

I thought that this would give 110 or 6, but it seems like either I'm misunderstanding the & operator. What am I doing wrong here or misunderstanding in the above?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58

1 Answers1

4

Bitwise & gives you a 1 in a bit position only if all operands have a 1 in that position. You are looking for bitwise |.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • thank you. How would you refer to a 'bit position'? Is it usually called the "1's", "2s", "4s" ? Or 1st, 2nd, 3rd lsb, or how is it usually referred to? – samuelbrody1249 Mar 25 '20 at 16:07
  • You read bits from right to left. The number at the right end is the least important bit, 0b0101 would be = 1*1 + 0*2 + 1*4 + 0*8 – sergenp Mar 25 '20 at 16:13
  • @sergenp got it, so in the above would you say "there is a one in the one's position, a 0 in the two's position", or or how you directly reference where the bit is? – samuelbrody1249 Mar 25 '20 at 16:16
  • 1
    @samuelbrody1249 1st lsb 2nd lsb...(LSB0, LSB1...) is one of the ways you can say it, as you can say 1st msb 2nd msb... (MSB0, MSB1...) – sergenp Mar 25 '20 at 16:21