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