下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
下面的位运算符在现实世界中有哪些用例?
和 XOR 不 或 左/右转
当前回答
这是一个从字节格式的位图图像中读取颜色的例子
byte imagePixel = 0xCCDDEE; /* Image in RRGGBB format R=Red, G=Green, B=Blue */
//To only have red
byte redColour = imagePixel & 0xFF0000; /*Bitmasking with AND operator */
//Now, we only want red colour
redColour = (redColour >> 24) & 0xFF; /* This now returns a red colour between 0x00 and 0xFF.
我希望这个小例子可以帮助....
其他回答
在当今现代语言的抽象世界里,没有太多。File IO是一个容易想到的方法,尽管它是在已经实现的东西上执行按位操作,而不是实现使用按位操作的东西。尽管如此,作为一个简单的例子,这段代码演示了在c#中删除文件上的只读属性(这样它就可以与指定FileMode.Create的新FileStream一起使用):
//Hidden files posses some extra attibutes that make the FileStream throw an exception
//even with FileMode.Create (if exists -> overwrite) so delete it and don't worry about it!
if(File.Exists(targetName))
{
FileAttributes attributes = File.GetAttributes(targetName);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
File.SetAttributes(targetName, attributes & (~FileAttributes.ReadOnly));
File.Delete(targetName);
}
As far as custom implementations, here's a recent example: I created a "message center" for sending secure messages from one installation of our distributed application to another. Basically, it's analogous to email, complete with Inbox, Outbox, Sent, etc, but it also has guaranteed delivery with read receipts, so there are additional subfolders beyond "inbox" and "sent." What this amounted to was a requirement for me to define generically what's "in the inbox" or what's "in the sent folder". Of the sent folder, I need to know what's read and what's unread. Of what's unread, I need to know what's received and what's not received. I use this information to build a dynamic where clause which filters a local datasource and displays the appropriate information.
下面是枚举是如何组合在一起的:
public enum MemoView :int
{
InboundMemos = 1, // 0000 0001
InboundMemosForMyOrders = 3, // 0000 0011
SentMemosAll = 16, // 0001 0000
SentMemosNotReceived = 48, // 0011
SentMemosReceivedNotRead = 80, // 0101
SentMemosRead = 144, // 1001
Outbox = 272, //0001 0001 0000
OutBoxErrors = 784 //0011 0001 0000
}
你明白这是怎么回事了吗?通过与“收件箱”枚举值InboundMemos加上(&),我知道InboundMemosForMyOrders在收件箱中。
下面是该方法的简化版本,它构建并返回为当前选择的文件夹定义视图的过滤器:
private string GetFilterForView(MemoView view, DefaultableBoolean readOnly)
{
string filter = string.Empty;
if((view & MemoView.InboundMemos) == MemoView.InboundMemos)
{
filter = "<inbox filter conditions>";
if((view & MemoView.InboundMemosForMyOrders) == MemoView.InboundMemosForMyOrders)
{
filter += "<my memo filter conditions>";
}
}
else if((view & MemoView.SentMemosAll) == MemoView.SentMemosAll)
{
//all sent items have originating system = to local
filter = "<memos leaving current system>";
if((view & MemoView.Outbox) == MemoView.Outbox)
{
...
}
else
{
//sent sub folders
filter += "<all sent items>";
if((view & MemoView.SentMemosNotReceived) == MemoView.SentMemosNotReceived)
{
if((view & MemoView.SentMemosReceivedNotRead) == MemoView.SentMemosReceivedNotRead)
{
filter += "<not received and not read conditions>";
}
else
filter += "<received and not read conditions>";
}
}
}
return filter;
}
非常简单,但在抽象级别上是一个整洁的实现,通常不需要按位操作。
我经常使用位操作将选项的组合存储在一个整数中。
int options = 0;
其中OPTION1可以定义为1,OPTION2定义为2,OPTION3定义为4,OPTION4定义为8,OPTION5定义为16,…
void addOption(int option)将使用|操作符向options中添加一个选项。
boolean hasOption(int option)将使用&操作符来测试选项中的选项。
Bitwise operators are useful for looping arrays which length is power of 2. As many people mentioned, bitwise operators are extremely useful and are used in Flags, Graphics, Networking, Encryption. Not only that, but they are extremely fast. My personal favorite use is to loop an array without conditionals. Suppose you have a zero-index based array(e.g. first element's index is 0) and you need to loop it indefinitely. By indefinitely I mean going from first element to last and returning to first. One way to implement this is:
int[] arr = new int[8];
int i = 0;
while (true) {
print(arr[i]);
i = i + 1;
if (i >= arr.length)
i = 0;
}
这是最简单的方法,如果你想避免if语句,你可以像这样使用模方法:
int[] arr = new int[8];
int i = 0;
while (true) {
print(arr[i]);
i = i + 1;
i = i % arr.length;
}
这两种方法的缺点是,模运算符是昂贵的,因为它在整数除法后寻找余数。第一个方法在每次迭代中运行if语句。然而,如果你的数组长度是2的幂,你可以很容易地生成一个像0 ..长度- 1,使用&(位和)操作符,如I & Length。知道了这些,上面的代码就变成了
int[] arr = new int[8];
int i = 0;
while (true){
print(arr[i]);
i = i + 1;
i = i & (arr.length - 1);
}
下面是它的工作原理。在二进制格式中,所有2的幂减去1的数都只用1表示。例如,二进制的3是11,7是111,15是1111,等等,你懂的。现在,如果你用任意一个数对一个只由1组成的二进制数,会发生什么?假设我们这样做:
num & 7;
如果num小于或等于7,那么结果将是num,因为每个加1的&-ed就是它自己。如果num大于7,在&操作期间,计算机将考虑7的前导零,当然,在&操作后,这些前导零将保持为零,只有后面的部分将保留。比如二进制的9和7
1001 & 0111
结果将是0001,它是十进制的1,并定位数组中的第二个元素。
如果你想计算你的数字mod(%) 2的某次方,你可以使用yourNumber & 2^N-1,在这种情况下,它与yourNumber % 2^N相同。
number % 16 = number & 15;
number % 128 = number & 127;
这可能只是作为模数运算的一种替代品有用,它的红利很大,是2^N。但即便如此,在我在。net 2.0上的测试中,它相对于模运算的速度提升也可以忽略不计。我怀疑现代编译器已经执行了这样的优化。有人知道更多吗?
例如,我使用它们从打包的颜色值中获取RGB(A)值。