What are bitwise shift (bit-shift) operators and how do they work?

后端 未结 11 1438
生来不讨喜
生来不讨喜 2020-11-21 04:46

I\'ve been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators) ...

What I\'m wondering

11条回答
  •  盖世英雄少女心
    2020-11-21 04:48

    Bit Masking & Shifting

    Bit shifting is often used in low-level graphics programming. For example, a given pixel color value encoded in a 32-bit word.

     Pixel-Color Value in Hex:    B9B9B900
     Pixel-Color Value in Binary: 10111001  10111001  10111001  00000000
    

    For better understanding, the same binary value labeled with what sections represent what color part.

                                     Red     Green     Blue       Alpha
     Pixel-Color Value in Binary: 10111001  10111001  10111001  00000000
    

    Let's say for example we want to get the green value of this pixel's color. We can easily get that value by masking and shifting.

    Our mask:

                      Red      Green      Blue      Alpha
     color :        10111001  10111001  10111001  00000000
     green_mask  :  00000000  11111111  00000000  00000000
    
     masked_color = color & green_mask
    
     masked_color:  00000000  10111001  00000000  00000000
    

    The logical & operator ensures that only the values where the mask is 1 are kept. The last thing we now have to do, is to get the correct integer value by shifting all those bits to the right by 16 places (logical right shift).

     green_value = masked_color >>> 16
    

    Et voilà, we have the integer representing the amount of green in the pixel's color:

     Pixels-Green Value in Hex:     000000B9
     Pixels-Green Value in Binary:  00000000 00000000 00000000 10111001
     Pixels-Green Value in Decimal: 185
    

    This is often used for encoding or decoding image formats like jpg, png, etc.

提交回复
热议问题