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'
else:
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)
try:
d = 10**(len(n)-n.index('.')-1)
n = int(d*N)
except(ValueError):
try:
d = 10**(len(n)-n.index('e')-1)
n = int(d*N)
except(ValueError):
d = 1
n = N
#finds the mantissa of N
if offset>=E:
if d == 1:
M = N*2**(-E+offset)
else:
M,r = divmod(n*2**(-E+offset),d)
if r>=d/2:
M+=1
else:
M,r = divmod(N,2**(E-offset))
if r >= (E-offset)/2:
M+=1
#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
bitrep(52,11)

### Like this:

Like Loading...

*Related*

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

In chrome, on a mac, “cmd+shift+v” keeps formatting when you paste. Useful trick, especially when dealing with Python.

Oy, actually have a code snippet coming up in tomorrow’s post. The *correct* way to get code and formatting is to use the

tag in html. I believe it is short for “pre-formatted”.