Luiz Siqueira Neto writes:
I know fine binarie numbers, but mabe um can give me some small example
code. : )Thanks about help me.
I replied:
Luiz:
Try the attached program. Continue trying different values in line 31 until
you feel that you understand it.-- Michael Chermside
But the attachment didn't work. So here's the program:
----- demo.py -----
def toBinary(x):
if False:
pass
elif x == 0:
return "0"
elif x == 1:
return "1"
elif x > 1:
if x % 2:
return toBinary(x >> 1) + "1"
else:
return toBinary(x >> 1) + "0"
elif x == -1:
return "(infinite 1's)"
elif x < -1:
return "(infinite 1's)0" + toBinary(-x - 1)
def printResults(op,x,y,xOPy):
if y == None:
print ('%s %i = %i ie: %s %s = %s'
% (op, x, xOPy,
op, toBinary(x), toBinary(xOPy)))
else:
print ('%i %s %i = %i ie: %s %s %s = %s'
% (x, op, y, xOPy,
toBinary(x), op, toBinary(y), toBinary(xOPy)))
for x, y in [(200, 3), (27, 13), (-6, 4)]:
printResults('>>', x, y, x >> y)
printResults('<<', x, y, x << y)
printResults('&', x, y, x & y)
printResults('|', x, y, x | y)
printResults('^', x, y, x ^ y)
printResults('~', x, None, ~x)
···
-------------------