【问题标题】:What is the purpose of the bitwise inclusive OR operator?按位包含 OR 运算符的目的是什么?
【发布时间】:2017-08-11 02:56:33
【问题描述】:

据我了解,按位包含 OR 运算符比较第一个和第二个操作数中的每一位,如果任一位为 1,则返回 1。Bjarne Stroustrup 像这样使用它(ist 是一个 istream 对象):

ist.exceptions(ist.exceptions()|ios_base::bad_bit);

我在编程方面的工作并不多,是否应该在我的待办事项清单上学习?我知道如果我有一个 int 并且值为 9,那么二进制将为 00001001,但仅此而已。我不明白他为什么会在他使用它的上下文中使用这个运算符。

【问题讨论】:

标签: c++ bit-manipulation


【解决方案1】:

在这种情况下,它只是意味着“打开一点”。

只是一个例子:我有一个字节 0100 0011 用作 8 个布尔值。我想打开第 4 位(即使第 4 个布尔值为真)

通过按位运算,它看起来像这样:[0100 0011] Bitwise-OR [0000 1000],它会给你0100 1011。这意味着,它只是将第 4 位更改为 true,而不管其原始值如何

【讨论】:

    【解决方案2】:

    您可以将其视为向一组现有选项添加选项的一种方式。如果您熟悉 linux,则可以类比:

    PATH = "$PATH:/somenewpath"
    

    这表示“我想要现有路径和这个新路径 /somenewpath”

    在这种情况下,他说“我想要异常中的现有选项,并且我也想要 bad_bit 选项”

    【讨论】:

    • 所以是用来把ios_base::badbit扔到ist.exceptions()那里可以处理的?
    • 是的,它将ios_base::badbit“添加”到现有的ist.exceptions(),而不必知道(或关心)它之前是什么。
    • 对于已经使用 C++ 几个月的人来说,位操作最终会成为我需要学习的东西吗?
    • @sS5H。是的。这是你应该早点而不是晚点学习的东西。它是基本的 C 或 C++。
    【解决方案3】:

    std::ios::exceptions 是一个函数,它获取/设置文件中的异常掩码,文件对象使用该掩码来决定在哪些情况下应该抛出异常。

    这个函数有两种实现方式:

    • iostate exceptions() const; // get current bit mask
    • void exceptions (iostate except); // set new bit mask

    您发布的语句使用ios_base::badbit 标志与当前在文件对象中设置的当前标志相结合,为文件对象设置了新的异常掩码。

    OR 位运算符通常用于使用已经存在的位域和新标志创建位域。它也可以用于将两个标志组合成一个新的位域。

    这是一个带有解释的示例:

    // Enums are usually used in order to represent 
    // the bitfields flags, but you can just use the
    // constant integer values.
    // std::ios::bad_bit is, actually, just a constant integer.
    enum Flags {
        A,
        B,
        C
    };
    
    // This function is similar to std::ios::exceptions
    // in the sense that it returns a bitfield (integer,
    // in which bits are manipulated directly).
    Something foo() {
      // Return a bitfield in which A and B flags
      // are "on".
      return A | B;
    }
    
    int main() {
      // The actual bitfield, which is represented as a 32-bit integer
      int bf = 0;      
    
      // This is what you've seen (well, somethng similar).
      // So, we're assigning a new bitfield to the variable bf.
      // The new bitfield consists of the flags which are enabled
      // in the bitfield which foo() returns and the C flag.
      bf = foo() | C;
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 2021-03-31
      • 1970-01-01
      • 2011-01-10
      • 2015-10-29
      • 2010-09-21
      相关资源
      最近更新 更多