1

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?

Miumen
  • 85
  • 6
  • 1
    Does this answer your question? [Converting an RGB color tuple to a hexidecimal string](https://stackoverflow.com/questions/3380726/converting-an-rgb-color-tuple-to-a-hexidecimal-string) – Fifi Mar 17 '23 at 07:49
  • No It doeasn't answer it only converts it to hext but i need to be in `0xRRGGBBAA` format – Miumen Mar 17 '23 at 07:52
  • Ah yes sorry, I read the format wrongly – Fifi Mar 17 '23 at 07:57

1 Answers1

1

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)

tmc
  • 389
  • 2
  • 6