SoFunction
Updated on 2025-03-06

How to add two bytes in C#

Discover problems

Anyone would want to add up? Not simple yet, use +.

byte a = 1;
byte b = 2;
byte c = a + b;

The above code cannot be compiled because when the compiler treats +, there are int additions, decimal additions, and string additions... There is no byte addition, so it will add with the closest int, and the naturally returned result is also int, and the int type cannot be directly assigned to a smaller byte type.

Solution

So, it has to be changed to this:

byte a = 1;
byte b = 2;
byte c = (byte)(a + b);

fine+=This problem does not exist,a += b It's no problem.

byte maximum value

byte minimum value is 0 and maximum value is 255, sobyte a = 256 It cannot pass the compilation.

And if + exceeds it is different.

byte a = 255;
a += 1; // The result here is 0
byte b = 150;
b += 150; // Here the result is 44,If changed to:b = (byte)(b + 150); It's the same。

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.