one-file-projects/ieee754.py

55 lines
1.1 KiB
Python
Raw Normal View History

def bin2hex(s):
ht = [ str(i) for i in range(10) ] + [ "A","B","C","D","E","F" ]
h = ""
while s != "":
h = ht[int(s[-4:],2)] + h
s = s[:-4]
return "0x"+h
def to_mantisse(d,n=23):
s = ""
for i in range(n):
d *= 2
s += str(int(d)%2)
return s
def to_binary(d,n=8):
s = ""
for i in range(n):
s = str(d & 1) + s
d = d >> 1
return s
def to_ieee754(d,el,ml):
if d < 0:
s = 1
d *= -1
else:
s = 0
g = 0
while d >= 2:
d /= 2
g += 1
while d <= 0.5:
d *= 2
g -= 1
bias = 2**(el-1)-1
e = g+bias
return str(s)+to_binary(e,n=el)+to_mantisse(d,n=ml)
def to_ieee754_single(d):
return to_ieee754(d,el=8,ml=23)
def to_ieee754_double(d):
return to_ieee754(d,el=11,ml=52)
def to_ieee754_single_hex(d):
return bin2hex(to_ieee754_single(d))
def to_ieee754_double_hex(d):
return bin2hex(to_ieee754_double(d))
if __name__ == "__main__":
print(bin2hex(to_ieee754_double(-2.5)))
print(bin2hex(to_ieee754_double(-1.75)))