2

For some API Integration, I have an operation where I need to add two bytes and get a single byte as a result. It's some kind of a checksum. Now by nature there can happen overflows.

For example

byte a = 0xff
byte b = 0x01
byte results = a + b;

Is there a simple built-in syntax to avoid overflows to move on to the next bytes or do I have to do this on my own? e.g. subtract full bytes and so on? Didn't find an API for this, did I overlook something?

1
  • You can use checked to explicitly enable overflow checking, or unchecked to explicitly disable overflow checking. In short, in a checked block/ statement the runtime will throw a OverflowException if the addition overflows, in an unchecked block/ statement the addition will just silently overflow Commented Nov 22, 2021 at 9:15

2 Answers 2

5

When you add bytes the result, however, is int, e.g.

byte a = 100;
byte b = 200;

var result = a + b; // result == 300

Since both a and b are in 0..255 range the result will be in 0..510 range and no integer overflow is possible. But you want byte result and that's why you need a cast:

byte result = (byte) (a + b);

Here, .net can show two types of reaction:

  • check ans throw overflow exception
  • do not check and ignore overflow: 256 -> 0, 257 -> 1 etc.

We want second option and that's why unchecked:

byte result = unchecked((byte) (a + b));
Sign up to request clarification or add additional context in comments.

Comments

2

By default, C# doesn't check for integral overflows so this should just work.

However, if the project has enabled integral overflow checking you can suppress it for a code block by using the unchecked keyword, for example:

byte a = 0xff
byte b = 0x01

unchecked
{
    byte results = (byte) a + b;
}

Or

byte results = (byte) unchecked(a + b);

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.