本文介绍了我可以对byte []执行按位运算吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我说:
byte[] data = new byte[] { 1, 212, 29, 144 };
我想出办法进行按位与运算的唯一方法首先将byte []转换为uint:
The only way I'm able to figure out to do a bitwise AND & is by first converting the byte[] to a uint:
if ((BitConverter.ToUInt32(data,0)) & 0x7) == 1)
{
//If the last 3 bits are ...111, then do something
}
这看起来很丑.有没有更好的方法可以对byte []执行按位运算而不必转换为UInt?谢谢.
This seems ugly. Is there a better way to perform bitwise operations on a byte[] without having to convert to a UInt? Thanks.
推荐答案
不,.Net没有直接支持字节数组上的位操作.
No, there no direct support in .Net for bit operations on byte arrays.
您可以
- 转换为您在问题中显示的现有类型
- 自己对数组执行操作并使用数组
- 考虑是否 BigInteger 适用于您的情况(支持对任意长数字进行所有按位运算,但是没有直接在常规
long
值之外写入long constanst的方法) - 考虑是否 BitArray 适用于您的情况(如果您只需要检查/设置特定的位,则更好).
- convert to existing types like you show in the question
- implement operations on arrays yourself and use arrays
- consider if BigInteger works for your cases (supports all bitwise operation on arbitrary long numbers, but there sitll no direct way to write long constanst outside regular
long
values) - consider if BitArray works for your case (better if you just need to check/set particular bits).
这篇关于我可以对byte []执行按位运算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!