Reputation: 1493
How can I convert a hexadecimal color value (like #ff3ab4
) to a three-tuple RGB value like (128, 255, 0)
?
Upvotes: 0
Views: 1911
Reputation: 1836
The reason why the leading zero's are being omitted is because the string gets converted to a number and when you try to represent the number as a string again it won't show any leading 0's, since the number, which doesn't have a certain length, can't know that it originated from a string, which in turn does have a certain length.
In your case I assume you would like to return the seperate A, R, B and G sections as a nicely formatted string. If you want to do this manually, I would do the following:
def colorComponents(hexAsString):
def uniformLength(string):
return string[:2] + "".zfill(10-len(string)) + string[2:]
re = []
re.append(str(hex(int(hexAsString, 16) & int("0xFF000000", 16))))
re.append(str(hex(int(hexAsString, 16) & int("0x00FF0000", 16))))
re.append(str(hex(int(hexAsString, 16) & int("0x0000FF00", 16))))
re.append(str(hex(int(hexAsString, 16) & int("0x000000FF", 16))))
for i in range(len(re)):
re[i] = uniformLength(re[i])
return re
Note that this is not optimized performance-wise in any way. :) You should use integers straight away (like using 255 instead of int("0xFF000000", 16)). This way though you can clearly see the bitmasks im using to filter out the separate components as hexadecimal numbers.
I am fairly certain there are things like string formatters as well that would do the job for having numbers represented as pretty strings, but I never used them so I can't tell you how a solution with those would look like :)
Edit: In case it is unclear to you how the bit-masks work that I used, here's a (hopefully) simple example: assume you have 2 bytes of data represented in their bit-form:
bytes0 = 0011 0101
bytes1 = 0000 1111
the &
operator is a bit-wise AND operator.
bytesAND = bytes0 & bytes1
bytesAND
now looks like this:
0000 0101
Upvotes: 2
Reputation: 2491
>>> bit32_to_bytes = lambda x: [255 & (x >> 8 * i) for i in (0,1,2,3)]
>>> bit32_to_bytes(0xFFEE2200)
[0L, 34L, 238L, 255L]
Some explanation:
>>> bin(0xFF00)
'0b1111111100000000' # this is string, not a number
>>> bin(0xFF00 >> 8) # shift right by 8 bits
'0b11111111' # leading zeros striped
>>> bin(0xA0FF00)
'0b101000001111111100000000' # 24-bit number
>>> bin(0xA0FF00 >> 8) # shift by 1 byte (drop the lowest byte)
'0b000000001010000011111111' # leading zeros added by myself!
>>> bin(255 & (0xA0FF00 >> 8)) # shift right (by 1 byte) and mask (get last byte)
'0b000000000000000011111111' # leading zeros added by myself!
After masking y = 255 & x
, y
receives the value of the low byte in the number x
.
y = 255 & (x >> 8 * n)
-> y = n-th byte from x
Upvotes: 1