I have an rbga color in format of r = 255, g = 0, b = 0, a = 255 and I Need to convert it to a 32 bit int in format of this: 0xRRGGBBAA
.
How should i Do this in python?
I have an rbga color in format of r = 255, g = 0, b = 0, a = 255 and I Need to convert it to a 32 bit int in format of this: 0xRRGGBBAA
.
How should i Do this in python?
You can try the following.
r, g, b, a = 255, 0, 0, 255 # red color
Shift the position of r
, g
, b
to the left by 24
, 16
and 8
bits, respectively to have their position in the 32-bit integer.
rgba_int = (r << 24) | (g << 16) | (b << 8) | a
or
rgba_int = (r << 24) + (g << 16) + (b << 8) + a
Print the result:
print(rgba_int)
Output is 4278190335
Convert the integer back to hexadecimal format to check:
rgba_hex = hex(rgba_int)
print(rgba_hex)
Output is 0xff0000ff
(red color)
From rgba_hex
, shift corresponding bits to the right, we have r
, g
, b
, and a
back to color format:
rgba_hex = int(rgba_hex, 16)
r = rgba_hex >> 24 & 0xFF
g = rgba_hex >> 16 & 0xFF
b = rgba_hex >> 8 & 0xFF
a = rgba_hex >> 0 & 0xFF
print(r)
print(g)
print(b)
print(a)
Output is 255, 0, 0, 255
(red color)