binary - 位和按位运算的用途是什么?

标签 binary bit-manipulation bitwise-operators bit

有人可以用非常简单的术语解释一下为什么我们需要按位运算符吗?我一个月前才开始编程。

我知道一切都以二进制形式存储。我了解计算机以 2 为基数进行计数。而且我了解按位运算符。我只是不明白什么样的编程需要使用位和按位运算符?

我试图在网上寻找答案,我读到了一些与二进制标志和残疾有关的内容,并且变得更加困惑。

我想我只是想知道,什么样的现实生活应用程序需要位和按位运算符?

最佳答案

您可以以非常简洁的格式打包数据。

x86 计算机可以寻址的最小量是一个字节 - 即 8 位。

如果您的应用程序有 24 个是/否标志( bool 值),您会将它们分别存储在 1 个字节中吗?那是 24 字节的数据。如果您使用位,则每个字节包含 8 个 bool 值 - 因此您只需要 3 个字节来表示 24 个是/否值:

> 1 Byte per flag:
> 0000 0000 = off
> 0000 0001 = on
> Easy to check: if(b == 0) { /* flag is off */ } else if(b == 1) { /* flag is on */ }

> 1 Bit per flag
> 0011 1101 = Flags 1, 4, 8, 16 and 32 are on, flags 2, 64 and 128 are off
> Packs 8 flags in 1 byte
> Harder to check:
> if( (b & 32) != 0) { /* Flag 32 is on */ }

这对于网络协议(protocol)和其他系统来说非常重要,因为每个字节都非常重要。

对于通用业务应用程序,通常不需要额外的复杂性,只需每个标志使用 1 个字节。

这不仅仅用于 bool 值。例如,某些应用程序可能想要存储两个从 0 到 15 的数字 - 例如 Commodore 64,它确实需要尽可能节省 RAM。一个字节可以容纳其中两个数字:

> Instead of interpreting this as 8 bits (ranging from 1 to 128)
> this is really two 4 bit numbers:
> 1001 0110
> First Number: 1001 = 1 + 8 = 9
> Second Number: 0110 = 2 + 4 = 6
>
> Getting the first number requires a bit shift to move them into position:
> (b >> 4) turns the above number into this:
> 0000 1001 - this can now be simply cast as a byte and returns 9
>
> The second number requires us to "turn off" the first 4 bits
> We use the AND operator for this: b = (b & 15)
> 15 in decimal is 0000 1111 in binary.
>
> 1001 0110 AND
> 0000 1111 =
> 0000 0110
>
> Once again, the result can be interpreted as a byte and results in the number 6

另一个非常巧妙的技巧是快速检查数字是偶数还是奇数。奇数始终设置最低有效位(1 位),而偶数始终保持清晰状态。

因此,您对 IsEven 的检查如下所示:

return (b & 1) == 0; // Bit 1 not set - number is even

(注意:根据语言的不同,编译器可能会决定优化内容,但简而言之,就是这样)

关于binary - 位和按位运算的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22603263/

相关文章:

c - 如何让我的代码正确打印二进制?

java - 存储二进制代码的字符串数组的内存大小

python - 如何在 python 中将字符串与二进制值连接起来?

c - 按位运算相当于大于运算符

c - 如何更改 uint32_t 变量中单个字节的值?

c++ - 这个 pData[1+2*i]<<8|pData[2+2*i] C++ 语法是什么意思?

c++ - 在 C++ 中使用 while 循环将二进制转换为十进制

java - 我可以执行哪些位掩码操作?

c - "? 1 : 0"是什么意思

javascript - 理解本例中的按位运算