I am trying to understand how unsigned overflow works with subtraction, so I wrote the following test to try:
#include<stdio.h>
#include<stdlib.h>
unsigned char minWrap(unsigned char a, unsigned char b) {
return a > b ? a - b : a + (0xff - b) + 1;
}
int main(int argc, char *argv[]) {
unsigned char a = 0x01, b = 0xff;
unsigned char c = a - b;
printf("0x%02x 0x%02x 0x%02x\n", a-b, c, minWrap(a,b));
return EXIT_SUCCESS;
}
Which gave as output:
0xffffff02 0x02 0x02
I would expect the result to be the same three times. My question is: is it always safe to add / subtract unsigned characters and expect them to wrap around 0xff?
Or more general, is it safe to calculate with uintN_tand expect the result to be modulo 2 ^ N?
source
share