c++visual-studio-2008subtractionunsigned-char

Subtraction operation on unsigned char


I have a curiosity about unsigned char. I did a subtraction operation on unsigned char accidentally.I know i am not supposed to do that. But i am bit curious about how a particular answer came. Can anybody explain this at bit level?

unsigned char x = 150;
unsigned char y = 229;

unsigned char z = x - y;

finally i got 177 for z during the debugging

I am running this code in visual studio 2008.


Solution

  • Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer.

    (C++11 standard, 3.9.1.5)

    On most platforms an unsigned char is 8 bits, so the result is 150 - 229 mod 256 = -79 mod 256 = 177.