擅长:python、mysql、java
<blockquote>
<p>what are bitwise operators actually used for? I'd appreciate some examples.</p>
</blockquote>
<p>位操作最常见的用途之一是解析十六进制颜色。</p>
<p>例如,这里有一个<a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a>函数,它接受类似<code>#FF09BE</code>的字符串,并返回其红色、绿色和蓝色值的元组。</p>
<pre><code>def hexToRgb(value):
# Convert string to hexadecimal number (base 16)
num = (int(value.lstrip("#"), 16))
# Shift 16 bits to the right, and then binary AND to obtain 8 bits representing red
r = ((num >> 16) & 0xFF)
# Shift 8 bits to the right, and then binary AND to obtain 8 bits representing green
g = ((num >> 8) & 0xFF)
# Simply binary AND to obtain 8 bits representing blue
b = (num & 0xFF)
return (r, g, b)
</code></pre>
<p>我知道有更有效的方法来实现这一点,但我相信这是一个非常简洁的示例,演示了移位和按位布尔运算。</p>