Why can't I do logical logic in bytes?

In C # (3.5) I will try the following:

byte byte1 = 0x00; byte byte2 = 0x00; byte byte3 = byte1 & byte2; 

and I get error message 132: "It is not possible to implicitly convert the type" int "to" byte. "An explicit conversion exists (do you miss the role?)". The same thing happens with | and ^.

What am I doing wrong? Why does this ask me about ints? Why can't I execute logic in bytes?

+6
c # byte boolean-logic
source share
2 answers

Different operators are not declared for byte - both operands get before int , and the result is int . For example, adding:

 byte byte1 = 0x00; byte byte2 = 0x00; byte byte3 = byte1 + byte2; // Compilation error 

Note that compound assignments work:

 byte1 += byte2; 

There was a recent SO question in this question. I agree that this is especially unpleasant for bitwise operations, although where the result should always be the same size, and this is a logically completely valid operation.

As a workaround, you can simply return the result in bytes:

 byte byte3 = (byte) (byte1 & byte2); 
+12
source share

Since byte (and short) types do not implement these operators

See Spec: 4.1.5

0
source share

All Articles