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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Boas Enkler
  • 12,264
  • 16
  • 69
  • 143
  • You can use [`checked`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/checked) to explicitly enable overflow checking, or [`unchecked`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/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 – MindSwipe Nov 22 '21 at 09:15

2 Answers2

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));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
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);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276