2007/2/19, Dick Moores <<a href="mailto:rdm@rcblue.com">rdm@rcblue.com</a>>:<div><span class="gmail_quote"></span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
At 02:17 AM 2/19/2007, Andre Engels wrote:<br><br>>To understand these operators, you will have to think of the numbers<br>>as binary numbers. Look at the digits. For two numbers x and y, x^y<br>>is the effect of doing an exclusive or on all digits (that is, 0^1 =
<br>>1^0 = 1 and 0^0 = 1^1 = 0), & of doing an and (1&1 = 1,<br>>1&0=0&1=0&0=0) and | is an or on all digits (1|1=1|0=0|1 = 1, 0|0 = 0).<br>><br>>So 5^8 = 110 ^ 1000 = 0110 ^ 1000 = 1110 = 13
<br>>and 13^8 = 1110 ^ 1000 = 0110 = 5<br><br>Thanks, Andre! I've got it for the three operators, for non-negative<br>integers. But I'm not sure I understand how negative integers work.<br>For example, is 3 & -3 = 1
<br>because it is 11 & -11 = 01, and that's because one of the first<br>digits of 11 and -11 is not 1, and both of their 2nd digits ARE 1, Q.E.D.?</blockquote><div><br>This has to do with the internal representation of negative numbers: -1 is represented as 111....111, with one 1 more than maxint. -2 is 111...110 and -3 is 111...101. Thus 3 & -3 is 11 & 111...101 = 1
<br></div><br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">Also, of what practical use are these things?<br></blockquote></div><br>I guess they have their uses for people accustomed to dealing with hardware. Apart from that, you can get a very space-efficient representation for multiple boolean variables. If you have what looks like an array of booleans, you could also represent it as a single natural number, for example [true, true, false, false, true, false] would then be 1*1 + 1*2 + 0*4 + 0*8 + 1*16 + 0*32 = 19. Using such a representation and the above operators would enable one to write
<br><br>z = x & y<br><br>instead of<br><br>z = [x[i] and y[i] for i in range(len(x))]<br><br>when modelling the same using lists.<br><br>Of course this does come at the price of complicating<br><br>x[i] = true<br><br>
to <br><br>x |= 2 ** i<br><br>which though not really longer does definitely look harder to understand.<br><br>-- <br>Andre Engels, <a href="mailto:andreengels@gmail.com">andreengels@gmail.com</a><br>ICQ: 6260644 -- Skype: a_engels