Im currently implementing a RC4 decryption and as this algorithm only operates on numbers between 0-255, I want to write as safe code as possible and properly use unsigned char variables instead of plain int ones.
Well, this although confronted me with a situation i cannot fortell what will happen.
Given are 3 vars i, j, k:
unsigned char i = 150;
unsigned char j = 155;
unsigned char k = 0;
Will the expression k = (i + j) % 256 properly set k to 49 or to 255 as i+j gets truncated?
Edit: fixed a “j” being spelled as “k”
The standard guarantees arithmetic on unsigned integer types to be arithmetic modulo
2^NwhereNis the number of value bits in the type, so the arithmetic will be correct.Section 3.9.1 (4) of the n3376 draft of the C++11 standard: