Integer range in C

Status
Not open for further replies.

ruturaj3

Journeyman
HI,

In C int is by default, signed short int so it uses 2 bytes(I m talking abt 16 bit compiler). and its range is -32768 to 32767.

And char uses 1 byte.

char ch = 1300, printf("%d",ch); prints 20.
coz, it takes only 8 bits.

1300 = 0101 0001 0100 in binary.

so when storing 1300 in char, it takes only 8 bits ie 0001 0100 wich is +20 (+ coz its signed bit is 0) in decimal.


So int a = 32767, printf("%d",a); prints output correctly ie 32767.

32772 = 1000 0000 0000 0100 in binary.
so if i tak 16 bits and since signed bit is 1 so - sign. so it should print - 4 na.

but int a = 32772, printf("%d",a); prints -32764 why ??? I m not getting tis point only.
 

astroutkarsh

Canon EOS 600D / 1000D
Its Range Problem.
You have added 5 in 32767 for 32772.
As Range Limit 32768 ==> -32768, 32769 ==> -32767..... 32772 ==> -32764.

At Binary Level try Addition of Two Binary Numbers with 16 bit Limitation.
Binary of 32767 + Binary of 5 (111111111111111 + 101)
 

Jayanth.M.P

Journeyman
you have crossed the bit level possible representation in binary mode, form here on each compiler reacts differently..........and if you are talking with respect to turbo c++....the above explanation is true.
 

grvpuri

Right off the assembly line
32772 = 1000 0000 0000 0100

Since negative numbers are stored in 2's complement form

Therefore, 1's complement of 1000 0000 0000 0100 = 0111 1111 1111 1011
2's complement of 1000 0000 0000 0100 = 0111 1111 1111 1100

which is 32764 in decimal.

Since sign bit is set, therefore answer is -32764

And yes, since integer size in C is platform dependent, so answer may be different on different platforms. The answer is same for all 16-bit compilers (not limited to only Turbo C++ 3.0)
 
Status
Not open for further replies.
Top Bottom