The struct
module is useful when you're trying to convert data to and from binary formats. However, recently I came across a file format specification that uses the binary16 floating point format. I looked through the Python documentation, but can't find anything that can convert to and from it. What would be the best way to convert this data to/from Python floats?
A sequence consisting of ones and zeroes is known as binary. Our traditional counting system with ten digits is known as decimal. <caption id=”attachment_824” align=”alignnone” width=”300”] Binary numbers and their decimal representation. The second parameter 2, tells Python we have a number based on 2 elements (1 and 0).
First of all, let us convert a binary string into an integer using the int () function in Python. the following is a simple Python program to convert a binary string into an integer: number= input ('Enter a Binary number:') dec_number= int (number, 2) print ('The decimal conversion is:', dec_number) print (type (dec_number))
In Python, If you want to convert a binary number into an octal, you have to convert the binary into a decimal first, and then convert this decimal number into an octal number. In the above program, we have used the for loop to convert a binary into decimal. Then we used the while loop to convert that decimal into an octal.
Honestly, a ‘10’ always represents the total number of digits in any base if you are writing the number in the respective number system. But it’s only funny in binary. When denoting hexadecimal numbers in Python, prefix the numbers with ‘0x’. Also, use the hex () function to convert values to hexadecimal format for display purposes.
You can do it roughly like you'd do it in C -- i.e., I think, roughly like this...:
def tofloat(b16):
sign = -1 if b16 & 0x8000 else +1
expo = ( b16 & 0x7C00 ) >> 10
prec = b16 & 0x03FF
if expo == 0:
return sign * (2.0 ** -24) * prec
elif expo == 0x1F:
return sign * float('inf')
prec |= 0x0400
return sign * (2.0 ** (expo - 25)) * prec
This guy's blog post gives an implementation in both and python. He uses the struct
module, then decodes it manually. It is not all that complicated a conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With