我可以对byte []执行按位运算吗? [英] Can I perform bitwise operations on byte[]?

查看:64
本文介绍了我可以对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.

您可以

  • 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 []执行按位运算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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