问题
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