variables - If i enter a value above 16383 in this C program that converts decimal to binary, it doesn't work. Why? -
this decimal binary converter, user inputs decimal number , binary version outputted. works fine except when input number (shown variable 'a' in code) greater 16383. i'm not quite sure why. curious thing when 16383 used input number, binary output long series of 1's. not sure if that's clue answer.
anyways, here's code:
#include<stdio.h> #include<conio.h> void main() { clrscr(); int a,x=1; printf("enter number in base 10:"); scanf("%d",&a);//max value:16383 reason?? while(x<=a) { x=x*2; } x=x/2; printf("\nbinary version:"); if(x==1) printf("1"); else { while(x>=1) { if(a/x==1) { printf("1"); a=a-x; } else printf("0"); x=x/2; } } getch(); }
are you, chance, working on 16-bit machine (where sizeof(int)
2
)?
because 16383 0x3fff
. 1 more 0x4000
, when doubled here...
while(x<=a) { x=x*2; }
...would give 0x8000
, wrap negative values on 16-bit machine.
(just in case not familiar 0x...
, hexadecimal notation, makes easier see bit patterns.)
int
signed type, i.e. can hold negative numbers. on most modern platforms, negatives significant bit set. 0x8000-0xffff
16bit machines, , 0x80000000-0xffffffff
on 32bit machines.
so, ever-larger positive numbers (0x7ffe
, 0x7fff
) can become small negative numbers (0x8000
). if you're using unsigned types (i.e. unsigned int
), similar "wraparound" "really large" "zero".
on machine, 16383 times 2 32766.
but 16384 times 2 (thanks limited range of numbers can represented in 16 bits) -2 -- @ point program breaks.
Comments
Post a Comment