[Tutor] Binary

Michael P. Reilly arcege@speakeasy.net
Fri, 11 May 2001 22:10:42 -0400 (EDT)


Timothy M. Brauch wrote
> 
> Okay, I know hex(x) will display x in hexadecimal and oct(x) will
> display x in octal, but how do I display x in binary?  I've tried
> seraching the python docs, but a search on binary turns up more on
> binary distributions and a search on base turns up stuff about base
> classes.

There isn't one really.  You have to whip up your own.

def bin(n):
  """Return a bit string representing the number, right-justified."""
  s = ''
  while n:
    if n & 01:
      s = '1' + s
    else:
      s = '0' + s
    n = n >> 1
  return s

> And another (hopefully) quick question, if & is a bit-wsie and, what
> does the command 'and' do?

It is called in some areas the "logical and".  It compares boolean values
instead of binary values, but otherwise it is the same.  With boolean
values the whole value is either true or false, instead of just one bit
in a number.

a = ''   # a is false
b = 'a'  # b is true
c = []   # c is false (length is zero)
d = [b]  # d is true  (length is not zero)
e = [a]  # e is true  (length is not zero, even tho a is false)
f = 0    # f is false
g = 1    # g is true
h = -1   # g is true (non-zero)

Using these booleans, logical "and" just extends the bit-wise "and".

  logical                            binary
a (false) and b (true) == false    0 (0000) & 1 (0001) == 0 (0000)
b (true)  and d (true) == true     1 (0001) & 1 (0001) == 1 (0001)
4 (true)  and 5 (true) == true     4 (0100) & 5 (0101) == 4 (0100)

This goes the same for logical "or" and logical "not" as well.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |