Posted By

jatkins on 10/02/10


Tagged

math decimal binary conversion Converter Maths


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Brunoofq


Binary to Decimal and Decimal to Binary converter


 / Published in: Pascal
 

Public domain.

  1. PROGRAM bindec;
  2. USES crt;
  3. VAR dec_begin, i: Integer;
  4. bin_number: String;
  5. zero_or_one, bin_or_dec: Char;
  6. bin: String;
  7. currHeading, intBinChar, x: Integer;
  8. dec: Real;
  9. repeat_char: Char;
  10. BEGIN
  11. clrscr;
  12. REPEAT
  13. WRITELN('To convert binary to decimal, press B; to convert decimal to binary, press D');
  14. READLN(bin_or_dec);
  15. IF (bin_or_dec='D') OR (bin_or_dec='d') THEN
  16. BEGIN
  17. WRITELN('Please enter a decimal number to convert to binary: ');
  18. READLN(dec_begin);
  19. REPEAT
  20. IF (dec_begin mod 2) = 0 THEN zero_or_one := '0'
  21. ELSE zero_or_one := '1';
  22. bin_number := bin_number + zero_or_one;
  23. dec_begin := dec_begin div 2;
  24. UNTIL dec_begin = 0;
  25. FOR i := Length(bin_number) DOWNTO 1 DO
  26. WRITE(bin_number[i]);
  27. WRITELN;
  28. END
  29. ELSE
  30. BEGIN
  31. WRITELN('Please enter a binary number to convert to decimal: ');
  32. READLN(bin);
  33. dec := 0;
  34. currHeading := 0;
  35. FOR i := Length(bin) DOWNTO 0 DO
  36. BEGIN
  37. IF currHeading > 0 THEN currHeading := currHeading * 2
  38. ELSE currHeading := 1;
  39. Val(bin[i], intBinChar, x);
  40. dec := dec + (intBinChar * currHeading);
  41. END;
  42. WRITELN(dec:10:0);
  43. END;
  44. WRITELN('Repeat? Y/N');
  45. READLN(repeat_char);
  46. UNTIL (repeat_char = 'N') OR (repeat_char = 'n');
  47. READLN;
  48. END.

Report this snippet  

You need to login to post a comment.