Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how 256 stored in char variable and unsigned char

Tags:

c++

c

char

memory

bits

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?

like image 758
Siva Kannan Avatar asked Feb 03 '14 14:02

Siva Kannan


People also ask

How much memory does an unsigned char have?

unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.

What is the difference between char and unsigned char?

So for signed char it can store value from -128 to +127, and the unsigned char will store 0 to 255. The basic ASCII values are in range 0 to 127. The rest part of the ASCII is known as extended ASCII. Using char or signed char we cannot store the extended ASCII values.


1 Answers

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.

like image 175
Mike Seymour Avatar answered Sep 27 '22 23:09

Mike Seymour