Advertisement
B1KMusic

[Figuring out base 4] Python implementation

Feb 24th, 2015
395
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. # v0.1: initial version. Only supported integers 0 - 1023
  2. # v0.2: Added arg to function to support integers beyond 1023
  3. # v0.3: Now it works with any integer that python can chew.
  4. # v0.3.1: Bugfix. b10_4(1) would crash, so I added a special case for anything below 10 (decimal 4)
  5. # v0.3.2: Bug affects any power of 4. So I changed the logic to fix that. < to <=
  6. # v0.3.3: Added test() function and added default arg for b10_4()
  7.  
  8. def test(r=0x1000):
  9.   for i in range(r):
  10.     print("%X of %X:\t%s" % (i,r,b10_4(i)))
  11.  
  12. def b10_4(N=0):
  13.   if N < 4: return str(N)
  14.   n = 0
  15.   i = 0
  16.   outs = ""
  17.   while 4**n <= N: n += 1
  18.   out = [0 for j in range(n)]
  19.   while n >= 0:
  20.     while N >= 4**n:
  21.       N -= 4**n
  22.       out[n] += 1
  23.     while N < 4**n:
  24.       n -= 1
  25.   out.reverse()
  26.   while i < len(out):
  27.     outs += str(out[i])
  28.     i += 1
  29.   return outs
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement