Binary to Decimal Conversion

0
lester pinto lester pinto is offline Offline | Aug 10th, 2006
Nice program!!!

i'm favorly new to C and was wondering how the
line b<<(len-k) worked... all i know its shifts the digits to the left..
but what i dont get is by how much..

....ie. bin<<1 =multiply it by 2 so what does len-k do in the above statement..

hope that doesnt' sound confusing..

and also what does teh sum stand for in "sum=sum+n*b"

cheers
 
0
declum declum is offline Offline | Sep 10th, 2006
your code is much long.. i found one in net
try it

  1. long bin2dec(char *s)
  2. {
  3. long r=0;
  4. for (; *s; r = (r<<1) | (*s++ - '0'));
  5. return r;
  6. }
Last edited by Nick Evan; Nov 20th, 2009 at 1:34 pm. Reason: Added code-tags
 
0
vegaseat vegaseat is offline Offline | Sep 15th, 2006
Good for you, but shorter is not always better. There is no error trapping, or explanation/comment how it works!
 
0
vegaseat vegaseat is offline Offline | Sep 15th, 2006
binary 10010 is calculated as 1*16+0*8+0*4+1*2+0*1 = decimal 18
hence b = b<<(len-k) does the multiplication by 1,2,4,8,16 ...

sum = sum + n * b;
// this will explain it ...
printf("%d*%d + ",n,b);
 
0
CSOL CSOL is offline Offline | Nov 20th, 2009
  1. /*conversion of binary number to decimal*/
  2. #include <stdio.h>
  3.  
  4. int main()
  5. {
  6. int binary, digit, base = 0, decimal = 0;
  7. printf("enter a binary number: ");
  8. scanf("%d", &binary);
  9. printf("Entered binary number is: %d\n", binary);
  10. while(binary)
  11. {
  12. digit = binary % 10;
  13. decimal += digit << base;
  14. base += 1;
  15. binary /= 10;
  16. }
  17. printf("decimal equivalent of the entered binary number is: %d", decimal);
  18. return 0;
  19. }
Last edited by Nick Evan; Nov 20th, 2009 at 1:33 pm.
 
-2
krishna5687 krishna5687 is offline Offline | Feb 6th, 2010
//decimal to binary
  1. #include<stdio.h>
  2. void main()
  3.  
  4. {
  5.  
  6. long int deci,rem,bin,p=1;
  7. printf("enter no");
  8. scanf("%ld",&deci);
  9. if (deci > 0)
  10.  
  11. {
  12. while (deci > 0)
  13.  
  14. {
  15. rem=deci%2;
  16. bin=rem*p+bin;
  17. p=p*10;
  18. deci=deci%2;
  19.  
  20. }
  21. printf("binary no is %ld",bin);
  22. //end of while loop
  23.  
  24. getchar();
  25.  
  26. }
  27.  
  28. //end of condition
  29.  
  30. else
  31.  
  32. printf("binary no for +tive integer only");
  33.  
  34. getchar();
  35.  
  36.  
  37. }
Last edited by adatapost; Feb 6th, 2010 at 9:43 am. Reason: Added [code] tags. Encase your code in: [code] and [/code] tags.
 
 

Tags
binary, conversion, decimal

Message:


Thread Tools Search this Thread



Tag cloud for binary, conversion, decimal
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2010 DaniWeb® LLC