2

I noticed that when Byte plus Byte, it will produce int, Is it possible to let byte a +byte b and produce 255 if it overflows?

Byte a=200;
Byte b=200
Byte output = (a+b); // now output equals 144, I want 255
2
  • Are you sure that that is a good idea? What's the requirement behind it? Just look: now output - a doesn't equal b anymore! Commented Sep 16, 2016 at 7:56
  • @BernhardHiller there are a lot of use cases where you want that behaviour ... e.g. calculations with colors ^^ Commented Sep 1, 2021 at 13:27

4 Answers 4

6

How about this (untested)?

byte output = (byte)(Math.Min(a + b, Byte.MaxValue));
Sign up to request clarification or add additional context in comments.

1 Comment

Probably byte.MaxValue is a bit more readable than magic constant 255
1

This usually happens when a number overflows which is not in a checked statement.

If you want it to produce 255 then the most simple option I can think of would be to use a ternary operation:

byte output = (int)a + (int)b > byte.MaxValue ? byte.MaxValue : a + b;

The other option I can think of would be to create your own data type that handles this for you.

Comments

1

Since a + b is of type int you can easily check:

  Byte a = 200;
  Byte b = 200

  byte result = a + b > byte.MaxValue ? byte.MaxValue : (byte) (a + b);

Comments

0

This will throw OverflowException:

checked
{
    Byte a=200;
    Byte b=200
    Byte output = (a+b);
}

And this way you can catch and process it:

Byte output;
try
{
    checked
    {
        Byte a=200;
        Byte b=200
        output = (a+b);
    }
}
catch(OverflowException e)
{
    output = Byte.MaxValue;
}
Console.WriteLine(output);

But I suggest you to control your flow yourself. Catching exceptions is bad approach, but if you have complex calculation, it can be troublesome. Just use Math instead:

var output = (Byte)Math.Min((int)a+b, Byte.MaxValue);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.