Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I do boolean logic on bytes?

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?

like image 937
Simon Avatar asked Jun 18 '09 09:06

Simon


People also ask

What is Boolean bitwise?

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.

How Boolean logic works?

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.

Where do we use Boolean logic?

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.

What is a Boolean operator PDF?

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.


1 Answers

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);
like image 101
Jon Skeet Avatar answered Oct 04 '22 15:10

Jon Skeet