130 days ago · Tech · hide · Fediverse post

It’s well known that you can convert the base 16 (hex) representation of an integer to the base 2 (binary) representation by simply converting each digit from hex to binary. For example, CAFEhex = 1100 1010 1111 1110two I imagine it’s less well known that you can do the same thing with floating point numbers. I wanted to find the binary representation of a floating point number using Python, and discovered that it has no function to do this. However, there is a method on floats to show a hex representation. For example, here’s the hex representation of π. >>>import math >>>(math.pi).hex() '0x1.921fb54442d18p+1' Curiously, the p+k part at the end is an exponent of 2, not an exponent of 16. So after we convert 1.921fb54442d18 to binary, we’ll need to multiply by 2, i.e. move the fractional point one space to the right. So first we convert 1.921fb54442d18hex to binary by converting 1, 9, 2, etc. each to binary. 1.1001 0010 0001 1111 1011 0101 0100 0100 0100 0010 1101 0001 1000two Then…

Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town