码迷,mamicode.com
首页 > 其他好文 > 详细

Bit Masking

时间:2020-05-19 12:29:32      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:like   ret   convert   ice   modified   sim   The   operator   similar   

Masking lets you modify a specific bit (or bits) using a bit pattern (called the mask) and a logical bitwise operator (AND, OR, or XOR). By changing the bits in the mask you will change which bits are modified by the operator. And by changing the operator, you will change how those bits are modified.

 

Take for example a = 10111001 (or 185 in decimal).

 

Using masking, you can set the last digit of a to 0 with the AND (&) operator and a mask of 11111110 (254 in decimal):

a    10111001

mask 11111110

b    10111000

Implemented, this would look something like:

b = a & mask

 

You can set the first 4 digits of a to 1 with the OR (|) operator and a mask of 11110000 (240 in decimal):

a    10111001

mask 11110000

b    11111001

This would look like:

b = a | mask

 

You can also toggle (meaning convert all 0‘s to 1‘s and vice versa) the entirety of a with the XOR (^) operator and a mask of 11111111 (255 in decimal):

a    10111001

mask 11111111

b    01000110

This would look like:

b = a ^ mask

 

Similarly, implement a mask using the bitwise Not operator (~)

Bit Masking

标签:like   ret   convert   ice   modified   sim   The   operator   similar   

原文地址:https://www.cnblogs.com/JasperZhao/p/12916008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!