Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binary16 in Python

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?

like image 732
icktoofay Avatar asked Jul 18 '10 04:07

icktoofay


People also ask

What are binary numbers in Python?

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).

How to convert a binary string to an integer in Python?

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))

How to convert a binary to an octal in Python?

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.

How to convert binary numbers to hexadecimal in Python?

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.


2 Answers

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
like image 65
Alex Martelli Avatar answered Sep 27 '22 23:09

Alex Martelli


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.

like image 41
zdav Avatar answered Sep 27 '22 23:09

zdav