ieee754 + rsa implementierung in python

This commit is contained in:
madmaurice 2015-11-29 23:54:47 +01:00
parent 49e072e29e
commit 585016e9d8
2 changed files with 70 additions and 0 deletions

54
ieee754.py Normal file
View file

@ -0,0 +1,54 @@
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)))

16
rsa.py Normal file
View file

@ -0,0 +1,16 @@
def e(m,e,n):
f = 1
print("%d ^ %d mod %d" %(m,e,n))
while e != 1:
print("= %d ^ %d * %d mod %d" % (m,e,f,n))
if e % 2 == 1:
f *= m
e -= 1
f = f % n
m = (m * m) % n
e /= 2
print("= %d * %d mod %d" % (m,f,n))
c = (m*f) % n
print("= %d" % c)
e(20,13,33)