RGB-HEX converter bitwise operations. https://pastebin.com/EMR6TP8c


#1

Hi
I have some troubles with understanding bitwise operations.

In “Advanced Topics in Python” I had done the RGB-HEX converter project, and I really cant understand why we two times in a row shifting variable hex_val to the right by eight bits.

So, take a look at the code for more understanding.
https://pastebin.com/EMR6TP8c

29, 31 lines of the code


#2

Since binary is base-2, then every shift to the left represents a doubling of the value. A shift to the right gives a value of half or 0.5 less than half since there are no decimals in binary.

3 << 1  ==  6
3 >> 1  ==  1

Going to look at your code now. Will return…

Your code is correct, so you must have had help or it was given in the instructions. Let’s run this in the console…

>>> x = int('FFFFFF', 16)
>>> x % 256
255
>>> x = x >> 8
>>> x % 256
255
>>> x = x >> 8
>>> x
255
>>> 

The first modulo is the blue value. To remove that from the full value we shift the number 8-bits to the right. The 8-bits there were on the right side are now dropped. The second modulo is the green value. Again, to remove those bits we shift one more time, 8-bits to the right. The value that remains is for red.

Let’s try this one another number,

>>> x = int('0FF0FF', 16)
>>> x % 256
255
>>> x = x >> 8
>>> x % 256
240
>>> x = x >> 8
>>> x
15
>>> 

#3

Oh, hmm. It’s looks very easy, and now I cant understand, why I could not understand such an obvious thing. Sorry for such a stupid question. Maybe I’m just too tired after university. I feel awkward. I did this project myself, but when I checked it, I got confused. So, thank you)

Best regards


#4

Looks are deceiving, especially when there are still holes in your knowledge base and comprehension. Never feel “stupid”, when you know you are giving it your all. The only stupid people I know are the ones who never try, or who give up too soon without trying harder. They will never learn. You, on the other hand appear to be giving your all to learning, so kudos! Pat yourself on the back and go easy on yourself. It’s not a contest or race. Success is always just around the corner.

Expect to hit lots of walls, and make lots of mistakes due to fuzzy understanding of concepts. Revel in mistakes and delight in what can be learned from them. They are a learner’s best friend.


#5

Addendum

Here are two basic functions with no validation…

def hex2rgb(hex_str):
    x = int(hex_str, 16)
    blue = x % 256
    x = x >> 8
    green = x % 256
    x = x >> 8
    red = x
    return "rgb({}, {}, {})".format(red, green, blue)

def rgb2hex(*args):
    red, green, blue = args
    return "#{}".format(hex((red << 16) + (green << 8) + blue)[2:])

print (hex2rgb("abcdef"))         # rgb(171, 205, 239)

print (rgb2hex(171, 205, 239))    # #abcdef