Page 1 of 1

Converting 24bits to 16bits color format error

Posted: Fri Aug 13, 2021 10:32 am
by darkthief
I'm trying to convert 24 bits to 16 bits but it gave me the error:
"NameError: name 'format' isn't defined"
How do I use the format method?

Code: Select all

def colorMenu():
    global r,g,b,
    blue = int(b/8)
    red = int(r/4)
    green = int(g/8)
    print('blue: '+bin(blue))
    print('red: '+bin(red))
    print('green: '+bin(green))
    newb = format(blue,'#07b')[2:]+'00000000000'
    newr = '00000' + format(red,'#08b')[2:]+ '00000'
    newg = '00000000000'+ format(green,'#07b')[2:]
    print('new blue: '+newb)
    print('new red: '+newr)
    print('new green: '+newg)
    colour = int(newb,2)+int(newr,2)+int(newg,2)
    print(bin(colour))
    nc = '0b'+format(colour,'#018b')[2:]
    print(nc)

Re: Converting 24bits to 16bits color format error

Posted: Fri Aug 13, 2021 11:42 am
by fdufnews
Perhaps a less convoluted solution

Code: Select all

Python 3.8.10 (default, Jun  2 2021, 10:49:15) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> r = 0xcf
>>> g = 0x78
>>> b = 0xa3
>>> # mask the unused bits
>>> nr = r & 0xf8
>>> ng = g & 0xfc
>>> nb = b & 0xf8
>>> print(hex(nr),hex(ng),hex(nb))
0xc8 0x78 0xa0
>>> # concatenate to make the 565 code
>>> f = nr << 8 | ng << 3 | nb >> 3
>>> print(hex(f))
0xcbd4
>>> 

Re: Converting 24bits to 16bits color format error

Posted: Fri Aug 13, 2021 2:33 pm
by darkthief
fdufnews wrote:
Fri Aug 13, 2021 11:42 am
Perhaps a less convoluted solution

Code: Select all

Python 3.8.10 (default, Jun  2 2021, 10:49:15) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> r = 0xcf
>>> g = 0x78
>>> b = 0xa3
>>> # mask the unused bits
>>> nr = r & 0xf8
>>> ng = g & 0xfc
>>> nb = b & 0xf8
>>> print(hex(nr),hex(ng),hex(nb))
0xc8 0x78 0xa0
>>> # concatenate to make the 565 code
>>> f = nr << 8 | ng << 3 | nb >> 3
>>> print(hex(f))
0xcbd4
>>> 
Thank you so much!
The display I think is actually in b,r,g format. Is it possible to just swap the order around?

Re: Converting 24bits to 16bits color format error

Posted: Fri Aug 13, 2021 8:14 pm
by fdufnews
You can easily change the format.
1) you may need to change the masks depending on which color is coded over 5 or 6 bits
2) you then change the order of the parameters in the last operation to place the 3 colors at the right place

Re: Converting 24bits to 16bits color format error

Posted: Sat Aug 14, 2021 6:16 am
by darkthief
Thanks for the help!