A function for displaying bits

A very busy week, so today’s post is just a code snippet which converts a decimal number to bits.  Notice that you can go inside the code and adjust how many bits are given to exponents and to the mantissa.  I’ve adjusted a bit to try to help the formatting, but I want to prioritize copying and pasting.  Let me know any problems/criticisms of the code!

from math import log,floor

def bitrep(mbits,ebits):
	#this function writes a float N = sign*M*2**(E-offset), where sign = 0 or 
	#1, M ranges from 2**0 up to 2**(mbits+1)-1 and E ranges from 2**0 up to 
	#2**(ebits+1)-1.  The numbers sign,M,N are then converted to binary, and 
	#sign,M,N are then returned.  To get the bit representation of a double, 
	#set mbits = 52, ebits = 11.
	mbits +=1
	offset = 2**(ebits-1)-1
	N = input('What decimal do you want the bit representation of?\n> ')

	#find the sign of the number
	if N >= 0:
		S = '0'
		S = '1'

	N = abs(N)
	#find the size of the number's exponent
	E= int(floor(log(N,2)))+offset-mbits

	#convert N into the fraction n/d, where d is a power of 10.
	n = str(N)
		d = 10**(len(n)-n.index('.')-1)
		n = int(d*N)
			d = 10**(len(n)-n.index('e')-1)
			n = int(d*N)
			d = 1
			n = N

	#finds the mantissa of N
	if offset>=E:
		if d == 1:
			M = N*2**(-E+offset)
			M,r = divmod(n*2**(-E+offset),d)
			if r>=d/2:
		M,r = divmod(N,2**(E-offset))
		if r >= (E-offset)/2:

	#converts both the exponent and mantissa to binary
	Ebin = bin(E-1)
	Ebin = Ebin[Ebin.index('b')+1:]
	Mbin = bin(M)[3:]

	#pads each number up to the total number of bits
	Ebin = Ebin.zfill(ebits)
	Mbin = Mbin.zfill(mbits)
	#cuts the mantissa back down to mbits of length, if necessary
	Mbin = Mbin[:mbits-1]

	#print out with the mantissa and exponent, then carrying out the 
	#calculation with python, then in bits
	print N,'\t"="',M,'* (2**[',E,'-',offset,'])\n','\t = ',M*(2**(E-offset)),'\n',S,Ebin,Mbin


3 comments on “A function for displaying bits

  1. Leonid Kovalev says:

    How did you manage to preserve the whitespace in the code when pasting it to WP? It even overlaps another column.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s