将 10 进制数转换为 256 进制数

Convert number base 10 to base 256

我在 Python 中创建了这个函数,它将 10 进制数转换为 256 进制数。 每次转换的结果必须是一个元组 (x,x,x),因此它可以解释为颜色 (rgb)。

25 -> (0,0,25) == 0256^2 + 0 256^1 + 25* 256^0 = 0+0+25 = 25

300 -> (0,1,44) == 0*256^2 + 1 * 256^1 + 44 * 256^0= 256+44 = 300

123456 -> (1, 226, 64) == 1*256^2 + 226 * 256^1 + 64 * 256^0 = 65536 + 57856 + 64 = 123456

请问有没有更好的方法让代码更易读,更快(可能避免太多循环)?

def convertBase256(n):
counter = 0
counter1 = 0
counter2= 0
if n < 256:
    return((0,0,n))
elif n >= 65536:
    while True:
        n -= 65536
        counter += 1
        if n== 0:
            return((counter,0,0))
            break
        elif n < 0:
            n += 256**2
            counter -=1
            while True:
                n -= 256
                counter2+= 1
                if n== 0:
                    return((counter,counter2,0))
                elif n < 0:
                    n += 256
                    counter2-= 1
                    return((counter,counter2,n))
elif n >= 256:
     while True:
        n -= 256
        counter1 += 1
        if n== 0:
            return((0,counter1,0))
        elif n < 0:
            n += 256
            counter1 -= 1
            return((0,counter1,n))
def convertBase256(n):
 rgb=tuple((n >> Val) & 255 for Val in (16, 8, 0))
 return rgb

整数类型内置了这个:

>>> help(int.to_bytes)
Help on method_descriptor:

    to_bytes(self, /, length, byteorder, *, signed=False)
        Return an array of bytes representing an integer.
    
        length
          Length of bytes object to use.  An OverflowError is raised if the
          integer is not representable with the given number of bytes.
        byteorder
          The byte order used to represent the integer.  If byteorder is 'big',
          the most significant byte is at the beginning of the byte array.  If
          byteorder is 'little', the most significant byte is at the end of the
          byte array.  To request the native byte order of the host system, use
          `sys.byteorder' as the byte order value.
        signed
          Determines whether two's complement is used to represent the integer.
          If signed is False and a negative integer is given, an OverflowError
          is raised.

您的代码生成长度为 3 的无符号大端结果,作为整数值的元组。 bytes 对象是一个序列,当您对其进行迭代时,它会为您提供字节,因此我们可以将其直接提供给 tuple 以进行必要的转换。因此:

def convertBase256(n):
    return tuple(n.to_bytes(3, 'big'))

我们完成了。