SETTING BINARY VIA RGB EXAMPLE

Setting 0bRGB (3-bit Binary Color)

In this example, each of R, G, and B can be either off (0) or on (1). This creates a simple 3-bit binary representation:

# Example: All colors ON (R=1, G=1, B=1)
>>> R = 1; G = 1; B = 1
>>> bin(R << 2 | G << 1 | B)
'0b111'

# Same example, represented in hexadecimal
>>> hex(R << 2 | G << 1 | B)
'0x7'

Setting 0bRRRRRRRRGGGGGGGGBBBBBBBB (24-bit RGB Color)

In this case, each R, G, and B can take a value in the range of 0 to 255 (8 bits each). The combined 24 bits represent the full RGB color in binary or hexadecimal:

# Example: Full white (R=255, G=255, B=255)
>>> R = 255; G = 255; B = 255
>>> bin(R << 16 | G << 8 | B)
'0b111111111111111111111111'

>>> hex(R << 16 | G << 8 | B)
'0xffffff'

# Example: Custom color (R=255, G=100, B=255)
>>> R = 255; G = 100; B = 255
>>> hex(R << 16 | G << 8 | B)
'0xff64ff'

EXTRACTING RGB VALUES

My Initial Implementation

Below is an attempt to extract R, G, and B values from a 24-bit hex color 0x123456. Each color is isolated using a combination of bitwise AND (&) and bitwise shift (>>) operations.

Extracting as Hexadecimal:

# Blue (bits 0–7)
>>> hex(0x123456 & 0xFF)
'0x56'

# Green (bits 8–15)
>>> hex((0x123456 & 0xFF << 8) >> 8)
'0x34'

# Red (bits 16–23)
>>> hex((0x123456 & 0xFF << 16) >> 16)
'0x12'

Extracting as Decimal:

# Red
>>> ((0x123456 & 0xFF << 16) >> 16)
18

# Green
>>> ((0x123456 & 0xFF << 8) >> 8)
52

# Blue
>>> (0x123456 & 0xFF)
86

Why This Needs Improvement

The above implementation has a subtle issue: operator precedence. The << operator has lower precedence than the & operator. This means expressions like 0xFF << 8 are evaluated later than the masking (&), leading to incorrect results.


Better Implementation

This corrected implementation ensures the precedence of operations is handled properly. Here’s the proper way to extract each color channel from 0x123456:

# Red (bits 16–23)
R = hex((0x123456 >> 16) & 0xFF)

# Green (bits 8–15)
G = hex((0x123456 >> 8) & 0xFF)

# Blue (bits 0–7)
B = hex(0x123456 & 0xFF)

Result (Hexadecimal):

  • Red: '0x12'
  • Green: '0x34'
  • Blue: '0x56'

To extract the values in decimal:

# Red
R_dec = (0x123456 >> 16) & 0xFF

# Green
G_dec = (0x123456 >> 8) & 0xFF

# Blue
B_dec = 0x123456 & 0xFF

Result (Decimal):

  • Red: 18
  • Green: 52
  • Blue: 86

Notes on the Correct Approach

  1. Shift First, Then Mask: Always shift bits to align the target color channel with the least significant byte before applying the mask (& 0xFF).
  2. Hexadecimal and Decimal Conversions: After extracting, use hex() for hexadecimal representation or directly work with the decimal values.

This method ensures consistent and accurate extraction of color channels, avoiding any pitfalls caused by operator precedence.

Leave a Reply

Your email address will not be published. Required fields are marked *