I am wondering how to convert the result returned by float.hex() to binary, for example, from 0x1.a000000000000p+2 to 110.1.
Can anyone please help? Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Explanation:
float.fromhexreturns a floatnum. We’d like its binary representation.{0:b}.format(...)returns binary representations of integers, but not floats.But if we multiply the float by enough powers of 2, that is, shift the binary representation to the left enough places, we end up with an integer,
shifted_num.Once we have that integer, we are home free, because now we can use
{0:b}.format(...).We can re-insert the decimal point (err, binary point?) by using a bit of string slicing based on the number of places we had shifted to the left (
exponent).Technical point: The number of digits in the binary representation of
shifted_nummay be smaller thanexponent. In that case, we need to pad the binary representation with more 0’s on the left, so binary slicing withbinary[:-exponent]won’t be empty. We manage that with'{0:0{1}b}'.format(...). The0{1}in the format string sets the width of the formated string to{1}, padded on the left with zeros. (The{1}gets replaced by the numberexponent.)