Skip to content

Instantly share code, notes, and snippets.

@danila-schelkov
Last active May 7, 2023 20:23
Show Gist options
  • Save danila-schelkov/f15f0820577302ca7064b91f329e3506 to your computer and use it in GitHub Desktop.
Save danila-schelkov/f15f0820577302ca7064b91f329e3506 to your computer and use it in GitHub Desktop.
A self-written function which can transform int value to float value and vice versa
def to_float(value_as_int: int) -> float:
binary = bin(value_as_int)
binary = binary[2:].zfill(32)
sign = -1 if binary[0] == '1' else 1
exponent = int(binary[1:9], 2) - 127
mantissa_base = binary[9:]
mantissa_bin = '1' + mantissa_base
mantissa = 0
val = 1
if exponent == -127:
if mantissa_base[1] == -1:
return 0
else:
exponent = -126
mantissa_bin = '0' + mantissa_base
for char in mantissa_bin:
mantissa += val * int(char)
val = val / 2
result = sign * 2 ** exponent * mantissa
return result
def to_int(value_as_float: float) -> int:
exponent = 0
sign = 1
if value_as_float == 0:
return 0
if value_as_float < 0:
sign = -1
value_as_float = -value_as_float
if value_as_float >= 2 ** -1022:
value = value_as_float
while value < 1:
exponent -= 1
value *= 2
while value >= 2:
exponent += 1
value /= 2
mantissa = value_as_float / 2 ** exponent
exponent += 127
as_integer_bin = '0'
if sign == -1:
as_integer_bin = '1'
as_integer_bin += bin(exponent)[2:].zfill(8)
mantissa_bin = ''
for x in range(24):
bit = '0'
if mantissa >= 1/2**x:
mantissa -= 1/2**x
bit = '1'
mantissa_bin += bit
mantissa_bin = mantissa_bin[1:]
as_integer_bin += mantissa_bin
as_integer = int(as_integer_bin, 2)
return as_integer
@danila-schelkov
Copy link
Author

I think i should rewrite this code and replace string concatenation with binary operations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment