Binary to Decimal

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • lmh86

    Binary to Decimal

    Should the following algorithm produce the binary equivalent of an inputed
    decimal value?

    ----------
    cout << "Decimal value: ";
    cin >> Decimal;
    Binary = 0;
    Remainder = Decimal;
    for(Power = 4; Power = -1; Power--) {
    Remainder = Decimal - (pow(2,Power));
    if(Remainder < 0) {
    Binary = Binary * 10;
    Remainder = Decimal;
    }
    if(Remainder >=0) {
    Binary = ((Binary * 10) + 1);
    Decimal = Remainder;
    }
    }
    cout << "Binary value: " << Binary << "\n";
    system("Pause") ;
    break;
    ----------

    Can anyone suggest any other methods that does not implement built-in
    functions?

    Please and thankyou.
  • Hendrik Schober

    #2
    Re: Binary to Decimal

    lmh86 <lmh86@discussi ons.microsoft.c om> wrote:[color=blue]
    > [...]
    > Can anyone suggest any other methods that does not implement built-in
    > functions?[/color]

    This sounds like some homework, so I will
    hint you into some direction, but won't
    post code.
    When you have this:
    int i;
    std::cin >> i;
    the value ist stored in 'i' in binary form.
    (That's the only way the computer knows.)
    If you look at the lowest bit of 'i' (by
    masking off the others) you know it's value.
    After that, you can shift 'i's content to
    the right one position and thus inspect the
    next bit at the same position.
    Feel free to ask if anything in this is not
    clear.
    [color=blue]
    > Please and thankyou.[/color]


    Schobi

    --
    SpamTrap@gmx.de is never read
    I'm Schobi at suespammers dot org

    "The presence of those seeking the truth is infinitely
    to be prefered to those thinking they've found it."
    Terry Pratchett


    Comment

    Working...