Python 将0-100(十进制百分比)转换为8位

Python 将0-100(十进制百分比)转换为8位,python,Python,我经常将0-100个十进制百分比转换为8位数字,用于读取值和控制内容。我一直使用简单的比率数学: def percent_to_byte(percent): if (percent >=0) and (percent <=100): return bytes([int(percent * 2.55)]) 输出: 0, 0.0, 0 1, 0.390625, 0 ... 127, 49.609375, 126 ... 255, 99.609375, 254

我经常将0-100个十进制百分比转换为8位数字,用于读取值和控制内容。我一直使用简单的比率数学:

def percent_to_byte(percent):
    if (percent >=0) and (percent <=100):
        return bytes([int(percent * 2.55)])
输出:

0, 0.0, 0
1, 0.390625, 0
...
127, 49.609375, 126
...
255, 99.609375, 254
在上面的每一行中,第一个值和最后一个值应该相同


在Python 3+中,给定介于0和100之间的实数集{x| 0≤ x≤ 100,x在R}中,返回8位二进制等效值。

百分比中的计算更改为字节

        return bytes([int((percent * 255)/100)])
并更改为循环中的缩放以

    y = x/2.55
则此循环不会打印任何差异:

for x in range(256): 
    y = x/2.55 
    z = int.from_bytes(percent_to_byte(y),sys.byteorder) 
    if z != x: 
        print(x, y, z)

您可以删除代码的冗余部分:


请更具体地说明您所面临的问题,例如,您已经有了一个简单的代码,为什么它不能满足您的需要。你到底想改进什么?我已经编辑了这个问题。感谢您指出我从未问过任何问题。StackOverflow是用于编程相关问题的。如果你问如何改进你的工作代码,考虑一下:@或b:我很生疏。你能写一个答案并拼出{bytes}解吗?@0stone0,我明白你的意思,但我的代码似乎返回了错误。似乎可以作为编程和代码审查离开。谢谢
for x in range(256): 
    y = x/2.55 
    z = int.from_bytes(percent_to_byte(y),sys.byteorder) 
    if z != x: 
        print(x, y, z)
def percent_to_byte(percent):
    if (percent >=0) and (percent <=100):
        return bytes([int(percent * 2.55)])
def percent_to_byte(percent):
    if 100 >= percent >= 0:
        return bytes([int(percent * 2.55)])