AND operator with byte operands

  • Thread starter The Last Danish Pastry
  • Start date
T

The Last Danish Pastry

void Test(byte x, byte y)
{
byte z = x & y;
}

This gives an error: "Cannot implicitly convert type 'int' to 'byte'. An
explicit conversion exists (are you missing a cast?)"

But, in "& Operator (C# Reference)" we read...

Binary & operators are predefined for the integral types and bool.

In "Integral Types Table (C# Reference)" we see that byte is an "integral
type".

What is going on? Programmers have been anding together two bytes to get
another byte for decades.
 
M

Marcel Müller

void Test(byte x, byte y)
{
byte z = x& y;
}

This gives an error: "Cannot implicitly convert type 'int' to 'byte'. An
explicit conversion exists (are you missing a cast?)"

But, in "& Operator (C# Reference)" we read...

Binary& operators are predefined for the integral types and bool.

In "Integral Types Table (C# Reference)" we see that byte is an "integral
type".

What is going on? Programmers have been anding together two bytes to get
another byte for decades.

Probably C# invokes the & operator with implicit propagation to int (as
well as C does). So the result of x&y is of type int rather than byte
(or short). So you have to write
byte z = (byte)(x & y);

The same applies to binary operator +, where the result will not
necessarily fit into a byte.


Marcel
 
A

Arne Vajhøj

Probably C# invokes the & operator with implicit propagation to int (as
well as C does). So the result of x&y is of type int rather than byte
(or short). So you have to write
byte z = (byte)(x & y);

The same applies to binary operator +, where the result will not
necessarily fit into a byte.

Exactly.

The issue is the same in Java (and Java also requires an
explicit cast).

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top