Binary to Decimal Conversion in C - Input Size Issue -
i have write c programme 1 of classes converts given binary number decimal. programme works smaller inputs, not larger ones. believe may due conversion specifier using scanf() not positive. code below
#include<stdio.h> #include<math.h> int main(void) { unsigned long inputnum = 0; int currentbinary = 0; int count = 0; float decimalnumber = 0; printf( "input binary number: " ); scanf( "%lu", &inputnum ); while (inputnum != 0) { currentbinary = inputnum % 10; inputnum = inputnum / 10; printf("%d\t%d\n", currentbinary, inputnum); decimalnumber += currentbinary * pow(2, count); ++count; } printf("decimal conversion: %.0f", decimalnumber); homecoming 0; } running little binary number:
input binary number: 1011 1 101 1 10 0 1 1 0 decimal conversion: 11 running larger binary number:
input binary number: 1000100011111000 2 399133551 1 39913355 5 3991335 5 399133 3 39913 3 3991 1 399 9 39 9 3 3 0 decimal conversion: 5264
when big number inputnum
currentbinary = inputnum % 10; its top portion gets "sliced off" on conversion int. if remain within bounds of unsigned long, switch currentbinary unsigned long well, , utilize unsigned long format specifier in printf. moreover, unsigned long may not sufficiently big on many platforms, need utilize unsigned long long.
demo.
better yet, switch reading input in string, validating zeros , ones (you have anyway) , conversion in cleaner character-by-character way. allow go beyond 64-bit of 19 binary digits have full-scale int input.
c binary decimal
No comments:
Post a Comment