2

I created this function in Python that converts a number in base 10 to base 256. The result of each conversion had to be a tuple (x,x,x) so it can be interpreted as a color (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

May I ask for some suggestions to make the code readable,faster (maybe avoiding too many loops) or if there is a better way.

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))
Dan2783
  • 53
  • 4
  • 1
    None of this is necessary, not even the tuples. Base 256 is how integers are stored in memory - a byte can have 256 values, so what you ask is the bytes of that number. All libraries can handle an integer as an ARGB or RGB value - that how RGB values are stored in memory. You could just extract the number's bytes if you want, but it's faster to just pass the 4-byte value to your library – Panagiotis Kanavos Nov 26 '20 at 08:10
  • Is this homework? You can use `to_bytes` to get the bytes but the tutor may actually want you to do the math. In real programming though one would **never** perform such calculations, as they are 1000s of times slower than the almost instantaneous extraction of bytes. And once again, all graphics libraries work with `int`s to *avoid* even that kind of extraction. In graphics, speed matters – Panagiotis Kanavos Nov 26 '20 at 08:16
  • Does this answer your question? [Converting int to bytes in Python 3](https://stackoverflow.com/questions/21017698/converting-int-to-bytes-in-python-3) – Panagiotis Kanavos Nov 26 '20 at 08:16
  • You'd expect it to, but the method there only works for single-byte results. – Karl Knechtel Nov 26 '20 at 08:18
  • Anyway, OP, you might also try https://codereview.stackexchange.com. – Karl Knechtel Nov 26 '20 at 08:19

2 Answers2

3

The integer type has this built-in:

>>> 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.

Your code produces an unsigned, big-endian result, of length 3, as a tuple of integer values. A bytes object is a sequence that gives you bytes when you iterate over it, so we can feed it directly to tuple to do the necessary conversion. Thus:

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

And we're done.

Karl Knechtel
  • 56,349
  • 8
  • 83
  • 124
1
def convertBase256(n):
 rgb=tuple((n >> Val) & 255 for Val in (16, 8, 0))
 return rgb
AziMez
  • 1,551
  • 1
  • 3
  • 15