使用按位运算符 [英] Using bitwise operators

查看:192
本文介绍了使用按位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习C#和跑翻过从我的旧的工作在C ++的一些熟悉的地面。我永远无法理解在实际应用中对位运算符的原因。我从来没有使用过,从未在使用它们的理由了。我一直在研究它们是如何工作;下面的例子显示了移位操作符。什么是位运算符,其使用的点,他们是如何工作的?

也许我缺少按位逻辑的东西。

 字节bitComp = 15; // bitComp = 15 = 00001111b
字节bresult =(字节)〜bitComp; // bresult = 240 = 11110000b

下面是为补〜位运算符的例子:

 字节bitComp = 15; // bitComp = 15 = 00001111b
字节bresult =(字节)〜bitComp; // bresult = 240 = 11110000b


解决方案

一个典型的用途是操纵在重新present相互排斥的'标志'位。

从MSDN例子:枚举类型

  [国旗]
枚举Days2
{
    无=为0x0,
    星期日=为0x1,
    星期一= 0X2,
    周二=为0x4,
    周三= 0x8中,
    周四= 0×10,
    周五0x20的=,
    周六= 0X40
}MyClass类
{
    Days2 meetingDays = Days2.Tuesday | Days2.Thursday;    Days2 notWednesday =〜(Days2.Wednesday);
}

又见栈 溢出问题的 最常见的C#位运算

I've been studying C# and ran accross some familiar ground from my old work in C++. I never understood the reason for bitwise operators in a real application. I've never used them and have never had in a reason to use them. I've been studying how they work; the example below shows the shift bitwise operator. What is the point of bitwise operators, their use and how they work?

Maybe I'm missing something in bitwise logic.

byte bitComp = 15;              // bitComp = 15 = 00001111b
byte bresult = (byte) ~bitComp; // bresult = 240 = 11110000b

Here's an example for the ~complement bitwise operator:

byte bitComp = 15;              // bitComp = 15 = 00001111b
byte bresult = (byte) ~bitComp; // bresult = 240 = 11110000b

解决方案

A typical use is manipulating bits that represent mutually exclusive 'flags'.

Example from MSDN: Enumeration Types

[Flags]
enum Days2
{
    None = 0x0,
    Sunday = 0x1,
    Monday = 0x2,
    Tuesday = 0x4,
    Wednesday = 0x8,
    Thursday = 0x10,
    Friday = 0x20,
    Saturday = 0x40
}

class MyClass
{
    Days2 meetingDays = Days2.Tuesday | Days2.Thursday;

    Days2 notWednesday = ~(Days2.Wednesday);
}

See also Stack Overflow question Most common C# bitwise operations.

这篇关于使用按位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆