how 256 stored in char variable and unsigned char

bit, c, c++, char, memory

Solution

Your guess is correct. Conversion to an unsigned type uses modular arithmetic: if the value is out of range (either too large, or negative) then it is reduced modulo 2N, where N is the number of bits in the target type. So, if (as is often the case) `char` has 8 bits, the value is reduced modulo 256, so that 256 becomes zero.

Note that there is no such rule for conversion to a signed type - out-of-range values give implementation-defined results. Also note that `char` is not specified to have exactly 8 bits, and can be larger on less mainstream platforms.

Problem

Up to 255, I can understand how the integers are stored in `char` and `unsigned char` ; ``` #include<stdio.h> int main() { unsigned char a = 256; printf("%d\n",a); return(0); } ``` In the code above I have an output of 0 for unsigned char as well as char. For 256 I think this is the way the integer stored in the code (this is just a guess): First 256 converted to binary representation which is 100000000 (totally 9 bits). Then they remove the remove the leftmost bit (the bit which is set) because the char datatype only have 8 bits of memory. So its storing in the memory as 00000000 , that's why its printing 0 as output. Is the guess correct or any other explanation is there?

Original source

Related problems