Reputation: 12557
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?
Upvotes: 2
Views: 307
Reputation: 186708
When you add byte
s 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:
256 -> 0
, 257 -> 1
etc.We want second option and that's why unchecked
:
byte result = unchecked((byte) (a + b));
Upvotes: 5
Reputation: 109577
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);
Upvotes: 2