This project was really straight-forward and easy to follow, but I still do not understand what some of the lines of code are doing. Can anyone explain what lines 9, and 14-20 are doing (they are labelled below)?
def rgb_hex(): red = int(raw_input('Enter a RED value: ')) # then determines if red is valid green = int(raw_input('Enter a GREEN value: ')) # then determines if green is valid blue = int(raw_input('Enter a BLUE value: ')) # then determines if blue is valid val = (red << 16) + (green << 8) + blue #line 9 print '%s' % (hex(val)[2:].upper()) def hex_rgb(): hex_val = raw_input('Enter a 6-digit HEX value: ') # determines if hex_val is valid hex_val = int(hex_val, 16) #line 14 two_hex_digits = 2 ** 8 blue = hex_val % two_hex_digits hex_val = hex_val >> 8 green = hex_val % two_hex_digits hex_val = hex_val >> 8 red = hex_val % two_hex_digits #line 20 print '%s %s %s' % (red, green, blue)
I tried to figure out what line 9 does by inserting a way to visibly see what each shift does:
for x in range(0,17): print red << x val = (red << 16) + (green << 8) + blue print '%s' % (hex(val)[2:].upper())
It appears that every shift over multiplies the value of red by 2. This means that:
val = red * 2 ** 16 + green * 2 ** 8 + blue
What exactly is the point of this operation?
line 14: What does the second parameter in
lines 15-20: Why do we divide by 2 ** 8? What are the right shifts doing? Blue is not shifted; green is shifted 8; red is shifted 16 (which mirrors what happens in function
rgb_hex(), so I assume that each shift indicates dividing by two this time around? Thanks for reading this long-winded post!