Converting integers to bytes

Let's say I have an integer, 13941412, which I want to divide by bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you must specify the number in BYTE, and then shift the bit. How do you make bytes in Python?

+3
source share
3 answers

To use bitwise mathematical operators, there are already "bytes":

def int_to_rgb(n):
    b = (n & 0xff0000) >> 16
    g = (n & 0x00ff00) >> 8
    r = (n & 0x0000ff)
    return (r, g, b)
+13
source

You can bitwise &with 0xff to get the first byte, then shift 8 bits and repeat to get the remaining 3 bytes.

: , . , :

r = num & 0x0000ff
g = (num & 0x00ff00) >> 8
b = (num & 0xff0000) >> 16
+2

Here's an optimization suggestion that applies in any language and does not harm readability.

Instead of this:

b = (n & 0xff0000) >> 16
g = (n &   0xff00) >> 8
r = (n &     0xff)

use this:

b = (n >> 16) & 0xff
g = (n >>  8) & 0xff
r =  n        & 0xff

Two reasons:

Fewer constants are not slower and can be faster.

Having smaller constants is not slower and can be faster - in a language such as C, a shorter machine instruction may be available; in a language such as Python, the implementation probably combines small integers.

0
source

Source: https://habr.com/ru/post/1739492/


All Articles