mathjax

Showing posts with label octal. Show all posts
Showing posts with label octal. Show all posts

Thursday, April 24, 2014

converting between decimal and octal

Two functions to perform conversion between the decimal and octal representation of integers.
#! /usr/bin/env python

def decimal_to_octal(decimal_num):
 i, o = 1, 0
 while decimal_num > 0:
  mod = decimal_num % 8
  o += (i * mod)
  decimal_num /= 8
  i *= 10
 return o

def octal_to_decimal(octal_num):
 i, d = 0, 0
 while octal_num > 0:
  mod = octal_num % 10
  d += (mod * 8**i)
  octal_num /= 10
  i += 1
 return d

if __name__ == '__main__':
 originals = range(10)
 octals = [decimal_to_octal(d) for d in originals]
 decimals = [octal_to_decimal(b) for b in octals]
 assert originals == decimals
 print 'originals:', originals
 print 'octals:', octals
 print 'decimals:', decimals

Sample output below.