How to Convert Float Number (Fraction) to Hexadecimal in Python?

  • 时间:2020-09-28 16:28:51
  • 分类:网络文摘
  • 阅读:82 次

We known that in Javascript, we can use the toString(16) to convert an integer to its hexadecimal representation. That works even for float numbrs, for example,

1
2
3
4
5
6
(0.5).toString(16)
"0.8"
(1.5).toString(16)
"1.8"
(0.3).toString(16)
"0.4ccccccccccccc"
(0.5).toString(16)
"0.8"
(1.5).toString(16)
"1.8"
(0.3).toString(16)
"0.4ccccccccccccc"

In python, you can do this using the following function FloatToHex that will print at most (by default) 16 decimal places in hexadecimal form.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import sys
 
def FloatToHex(x, k = 16):
    if x < 0: 
        sign = "-"
        x = -x
    else:
        sign = ""
    s = [sign + str(int(x)) + '.']
    x -= int(x)
    for i in range(k):
        y = int(x * 16)
        s.append(hex(y)[2:])
        x = x * 16 - y
    return ''.join(s).rstrip('0')
 
if __name__ == "__main__":
    print(FloatToHex(float(sys.argv[1])))
import sys

def FloatToHex(x, k = 16):
    if x < 0: 
        sign = "-"
        x = -x
    else:
        sign = ""
    s = [sign + str(int(x)) + '.']
    x -= int(x)
    for i in range(k):
        y = int(x * 16)
        s.append(hex(y)[2:])
        x = x * 16 - y
    return ''.join(s).rstrip('0')

if __name__ == "__main__":
    print(FloatToHex(float(sys.argv[1])))

Examples:

# python3 FloatToHex.py 0.5
0.8
# python3 FloatToHex.py 0.6
0.99999999999998
# python3 FloatToHex.py 0.3
0.4ccccccccccccc
# python3 FloatToHex.py 2.3
2.4cccccccccccc
# python3 FloatToHex.py -2.3
-2.4cccccccccccc

The complexity is O(1) if we consider the string manipulation is also O(1) and the hex function in Python runs at O(1) constant.

python How to Convert Float Number (Fraction) to Hexadecimal in Python? code code library programming languages python

python

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
已知被除数,除数,商与余数的和是235,已知商是27,余数是6,求除数。  图中几条直线、几条射线、几条线段?  滞尘是什么意思?  冬冬是2008年2月29日出生的,到2016年2月29日他一共过了几个生日?  饮料架上放有大、中、小三种包装的饮料  有一架天平和一个50克的砝码,如果要得到150克糖果  看似容易-六年级易错题集锦  从前往后数小明排在第7位  三年级上册第九单元思考题:学校举行乒乓球比赛  “先填空,再列综合算式”总出错怎么办 
评论列表
添加评论