In C# (3.5) I try the following:
byte byte1 = 0x00;
byte byte2 = 0x00;
byte byte3 = byte1 & byte2;
and I get Error 132: "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)". The same happens with | and ^.
What am I doing wrong? Why is it asking me about ints? Why can't I do boolean logic on bytes?
Along with integer operands, the bitwise OR can also be used with boolean operands. It returns true if at least one of the operands is true, otherwise, it returns false.
Boolean Logic is a form of algebra in which the variables have a logical value of TRUE or FALSE. AND = Can be thought of as BOTH. It requires that both or all objects (search terms) be present in the results. In online searching AND serves to narrow the search and is used for combining differing concepts.
Boolean logic and operators (based on Boolean algebra) are used in most information databases, providing the ability to combine synonyms and variant concepts together to access relevant items. AND, OR, and NOT are the basic Boolean connectors.
Boolean Operators are simple words used as conjunctions to combine or exclude keywords in a search…. giving you more focused and productive results that are appropriate to your needs.
Various operators aren't declared for byte
- both operands get promoted to int
, and the result is int
. For example, addition:
byte byte1 = 0x00;
byte byte2 = 0x00;
byte byte3 = byte1 + byte2; // Compilation error
Note that compound assignments do work:
byte1 += byte2;
There was a recent SO question on this. I agree this is particularly irksome for bitwise operations though, where the result should always be the same size, and it's a logically entirely valid operation.
As a workaround, you can just cast the result back to byte:
byte byte3 = (byte) (byte1 & byte2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With