Thursday 9 September 2010

Nice and simple Binary to Decimal algorithm.

Little function for converting binary to decimal, as their seems to be a lack of these code snippets. here we go, enjoy.

#include 

/*  This function takes a binary string and returns
    the decimal equivalent using the Positional notation  
    method. */
__int64 binToDec(char *binStr)
{
 __int64 pow = 1, dec = 0;
 for (int i = strlen(binStr)-1; i >= 0; i--)
 {
  dec += (binStr[i] == '1') ? pow : 0;
  pow *= 2;
 }
 return dec;
}

int main()
{
 std::cout << binToDec("1010");
 std::cin.get();
 return 0;
}

4 comments:

  1. butts

    http://kadams133.blogspot.com/

    ReplyDelete
  2. I was never good at programming.

    ReplyDelete
  3. BigLoser, that's a bit pessimistic, you may be surprised how good you are, just find some project that you enjoy doing.

    ReplyDelete
  4. Yooooooo
    http://kadams133.blogspot.com/

    ReplyDelete