C#。逻辑谜题与位操作。只有一个位被设置? [英] C#. Logical riddle with bit operations. Only one bit is set?

查看:100
本文介绍了C#。逻辑谜题与位操作。只有一个位被设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是很容易的C ++的人虽然。但有人问我如何做到这一点在C#。不应该有太大的差异。

如何找出是否一个长变量的仅一个位置?

我想不出任何东西,除了一些野蛮的力量转移所有位计数什么集。


解决方案

  

一个非负二进制整数值x,如果 A 2的幂(X及(X-1))使用2的补数算术0


2的方幂意味着单个位被置

<一个href=\"http://aggregate.org/MAGIC/#Is%20Power%20of%202\">http://aggregate.org/MAGIC/#Is%20Power%20of%202

编辑:

要允许零案件:

 布尔singleBit = X&GT; 0安培;&安培; (X及(X-1))== 0

This should be easy for C++ people though. But I was asked how to do it in C#. Shouldnt be much of difference.

How to find out if a long variable has only one bit set?

I cant think anything except some brutal force shifting all bits and counting whats set.

解决方案

A non-negative binary integer value x is a power of 2 if (x&(x-1)) is 0 using 2's complement arithmetic.

Powers of 2 would mean a single bit is set.

http://aggregate.org/MAGIC/#Is%20Power%20of%202

EDIT:

To allow for the zero case:

bool singleBit = x>0 && (x&(x-1))==0

这篇关于C#。逻辑谜题与位操作。只有一个位被设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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