Jump to content

Binary to Decimal and back

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
atomicSpatule

atomicSpatule

    Newbie

  • Members
  • Pip
  • 5 posts
I've written 2 functions for doing this, I havent tried to compile them, but as far as I can tell, they should work. What I want is some feedback, what do you think of it, how could you make it better, etc. I've put it in the C# section because it looks like C#, though I'm not sure if VS would take it :confused:

Here's the code :

private int BinToDec(bool[] bin, int lenght) {

  int i, dec;

  for(i = 0; i = lenght; i++){

    if(bin[lenght - i] = true){

      dec += Math.pow(2, i);

    }

  }

  return dec;

}


private bool[] DecToBin(int dec){

  bool match;

  int lenght;

  while(!match){

    if(dec < Math.pow(2, i)){

      match = true;

      break;

    }

    lenght++;

  }

  bool[] bin[lenght-1];

  int power = lenght;

  for(;lenght = 0; lenght--){

    if(BinToDec(bin, lenght-1) + Math.pow(2, lenght) < dec){

      bin[lenght] = true;

    }

    if(BinToDec(bin, lenght-1) == dec) return bin;

  }

}


Have a nice day, fellow programmers! :)

#2
Mathstar

Mathstar

    Newbie

  • Members
  • Pip
  • 6 posts
Goodluck!

#3
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
in DecToBin, i is not defined for use in the While loop. The While loop could also be cleaned up substantially. Using the BinToDec in the DecToBin function is also introducing a LOT of extra work.

It appears to be C++ code.

If you search in the forum, you should find an old discussion about doing conversions between binary and decimal.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog