Last active
October 13, 2015 11:38
-
-
Save bancek/4189813 to your computer and use it in GitHub Desktop.
IEEE 754
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct | |
from_hex = lambda hx: struct.unpack('>f', struct.pack('>I', hx))[0] | |
to_hex = lambda dc: '0x' + ''.join(['%.2x' % ord(x) for x in struct.pack('>f', dc)]) | |
chr_to_bin = lambda ch: ('0'*8 + bin(ord(ch))[2:])[-8:] | |
to_32_bits = lambda fl: '|'.join((lambda bits: [bits[:1], bits[1:9], bits[9:]])(''.join(map(chr_to_bin, struct.pack('>f', fl))))) | |
to_64_bits = lambda fl: '|'.join((lambda bits: [bits[:1], bits[1:12], bits[12:]])(''.join(map(chr_to_bin, struct.pack('>d', fl))))) | |
from_bits = lambda bs: from_hex(int(bs.replace('|', ''), 2)) | |
a = 0xfb | |
b = from_hex(0x80004800) | |
c = a * b | |
print to_32_bits(a) | |
# 0|10000110|11110110000000000000000 | |
print to_32_bits(b) | |
# 1|00000000|00000000100100000000000 | |
print to_32_bits(c) | |
# 1|00000000|10001101001100000000000 | |
print to_64_bits(c) | |
# 1|01110000000|0001101001100000000000000000000000000000000000000000 | |
print to_hex(c) | |
# 0x80469800 | |
print from_bits('1|00000000|00000000100100000000000') | |
# -2.582873329443503e-41 | |
print to_32_bits(0.0) | |
# 0|00000000|00000000000000000000000 | |
print to_32_bits(-0.0) | |
# 1|00000000|00000000000000000000000 | |
print to_32_bits(float('infinity')) | |
# 0|11111111|00000000000000000000000 | |
print to_32_bits(float('-infinity')) | |
# 1|11111111|00000000000000000000000 | |
print to_32_bits(float('nan')) | |
# 0|11111111|10000000000000000000000 | |
print to_32_bits(float('-nan')) | |
# 1|11111111|10000000000000000000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tisti, ki boste uporabljal tole skripto za preverjanje rezultata pri 2. domači nalogi za ars, namesto 0xfb(ki je zapisan s dvojiškim komplementom), pišite -0x5 in boste dobili pravilno rešitev.