Skip to content

Instantly share code, notes, and snippets.

@jaheba
Created October 24, 2011 14:17
Show Gist options
  • Select an option

  • Save jaheba/1309135 to your computer and use it in GitHub Desktop.

Select an option

Save jaheba/1309135 to your computer and use it in GitHub Desktop.
PT_I-Übung 1
#encoding: utf-8
from string import digits, ascii_uppercase
def base(b, n, symbols=digits+ascii_uppercase):
'return the nubmer `n` with base `b`'
if b > len(symbols):
raise IndexError('Not enough symbols to represent base')
digits = []
while True:
q, r = divmod(n, b)
digits.append(symbols[r])
n = q
if n == 0:
break
return ''.join(reversed(digits))
def complement(b, number, bits):
#in range?
if not (-b**(bits-1) <= number < b**(bits-1)):
raise IndexError('Number not representable with %s bits' %bits)
if number < 0:
return base(b, b**bits+number) #it's +number, since the number is negative
else:
return '{0:0>{bits}}'.format(base(b, number), bits=bits)
if __name__ == '__main__':
import sys
from jinja2 import Template
text = u'''Aufgabe c:
{% for n in [62, 1000, 1024, 100000, 1048576] %}
{{n}}
{% for b, bname in ((2, 'Binärsystem'), (8, 'Oktalsystem'), (16, 'Hexadezimalsystem'), (11, 'Basis 11')) %}{{bname}}: {{base(b, n)}}
{% endfor %}
{% endfor %}
Aufgabe d:
{% for n in -1, 1, 28, -35, -256, 257 %} ({{n}})
Base2 -> {{complement(2, n, 16)}}
Base16 -> {{complement(16, n, 16//4)}}
{% endfor %}
Aufgabe e:
{% for u in 'Æ', '£', '\u03c1', '\u2264' %} {{u}}: {{ord(u)}}
{% endfor %}'''
print Template(text).render(
base=base, ord=ord, complement=complement
).encode('utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment