Kia Azad
Kia Azad

Reputation: 186

strip hex to a single digit in string formating in python

I'm trying to convert RGB values to short hex format, I have the long version:

'#{:02x}{:02x}{:02x}'.format(r, g , b)

is it possible to get #fff instead of #ffffff without formatting the values one by one to take the first digits?

Edit: my code doesn't require much accuracy in colors so it accepts a shortened version of color hex code that each color is represented by a single digit and the second digit is omitted.

any value from 0 to 15 is considered 0

any value from 16 to 31 is considered 1

and so on...

Upvotes: 0

Views: 189

Answers (1)

EchoMike444
EchoMike444

Reputation: 1692

so you have this code to output a rgb value on 24 bits

print('#{:02x}{:02x}{:02x}'.format(r, g , b))

if you want to output a rgb value on 12 bits only when the value can be shortened

if (r % 17 == 0 and g % 17 == 0 and b % 17 == 0):
     print('#{:01x}{:01x}{:01x}'.format(r/17, g/17, b/17))
else:
     print('#{:02x}{:02x}{:02x}'.format(r, g , b))

if you encode a mono chromatic color in 8 bits you have 256 values between 0 and 255 , so you have 255 intervals .

if you encode a mono chromatic color in 4 bits you have 16 values between 0 and 15 , so you have 15 intervals .

so 255 / 15 => 17

Upvotes: 2

Related Questions