Created
August 26, 2018 19:41
-
-
Save vitaminac/8ed6fe10d0c47654277e026f9e2cf8c7 to your computer and use it in GitHub Desktop.
la representacion IEEE724 de un float
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
# coding=utf-8 | |
import ctypes, struct | |
from ctypes import c_uint, c_uint64, c_int64, c_uint32, c_ulong | |
class IEEE764F(ctypes.Structure): | |
_fields_ = [("mantissa", c_uint32, 23), | |
("exponent", c_uint32, 8), | |
("sign", c_uint32, 1)] | |
class BothFloat764(ctypes.Union): | |
_fields_ = [('Float', c_ulong), ('IEEE764F', IEEE764F)] | |
def floatToLong32(float_): | |
return struct.unpack('L', struct.pack('f', float_))[0] | |
class IEEEDoubleStruct(ctypes.Structure): | |
_fields_ = [("mantissa_low", c_uint64, 32), ("mantissa_high", c_uint64, 20), ("exponent", c_int64, 11), ("sign", c_uint64, 1)] | |
class Both(ctypes.Union): | |
_fields_ = [('Double', c_uint64), ('IEEEDoubleStruct', IEEEDoubleStruct)] | |
def doubleToLongLong(float_): | |
return struct.unpack('Q', struct.pack('d', float_))[0] |
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
# coding=utf-8 | |
import ctypes | |
import IEEE724 | |
class IEEE764Float: | |
def __init__(self, float_): | |
self.float_ = float_ | |
long32_ = IEEE724.floatToLong32(float_) | |
self.__ = IEEE724.BothFloat764(ctypes.c_uint32(long32_)) | |
@property | |
def binary(self): | |
return bin(self.__.Float) | |
@property | |
def mantissa(self): | |
return bin(self.__.IEEE764F.mantissa) | |
@property | |
def exp(self): | |
return bin(self.__.IEEE764F.exponent - 127) | |
@property | |
def sign(self): | |
return "negative" if self.__.IEEE764F.sign > 0 else "positive" | |
def __repr__(self): | |
return " ".join([self.sign, self.exp, self.mantissa]) | |
while True: | |
try: | |
# doubl = float(input("enter a double number ")) | |
# doubl = ctypes.c_double(doubl) | |
float_ = 56789.25 | |
# long32 = floatToLong32(float_) | |
# long32 = ctypes.c_uint32(long32) | |
# ctypes.cast(long, IEEEDoubleStruct) | |
# doubl = Both764(long32) | |
a = IEEE764Float(float_) | |
print(a) | |
break | |
except TypeError as e: | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment