Can I perform bitwise operations on byte[]?

丶灬走出姿态 提交于 2021-01-28 18:21:00

问题


Let's say I have:

byte[] data = new byte[] { 1, 212, 29, 144 };

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
}

This seems ugly. Is there a better way to perform bitwise operations on a byte[] without having to convert to a UInt? Thanks.


回答1:


No, there no direct support in .Net for bit operations on byte arrays.

You can

  • 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).



回答2:


I found this solution:

byte b1 = 0x11;
byte b2 = 0xF0;
byte b3 = (byte)(b1 & b2);


来源:https://stackoverflow.com/questions/38042496/can-i-perform-bitwise-operations-on-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!