Reputation: 21
I dont know what is the different these two code. Above only have single &
while below have &&
. I have an error for the above code. I dont how to solve it.
Cmd3[8] = (byte)(Length & 0xFF);
Cmd3[9] = (byte)(((Length >> 8) && 0xFF) ? -1 : 0);
Hope you guys can help me.
Upvotes: 2
Views: 1562
Reputation: 186833
You, probably, mean bitwise And: &
; another issue is that unlike C, C# doesn't implicitly convert integer 0
into bool
false
, and, finally, (byte) -1
conversion can cause OverflowException
:
// since -1 is out of byte range and you don't want exception to be thrown
// you have to (in general case) put "unchecked" to allow integer overflow
unchecked {
...
Cmd3[8] = (byte)(Length & 0xFF);
// != 0: C# can't convert int 0 into bool false
// &: bitwise And (not logical one)
Cmd3[9] = (byte)(((Length >> 8) & 0xFF) != 0 ? -1 : 0); // -1 can cause integer overflow
...
}
Upvotes: 2
Reputation: 361
The difference is that a single &
is a bitwise AND, while &&
is a boolean operator (which can only be applied to boolean operands).
You probably want the code to use single &
.
Upvotes: 1