Reputation: 555
I'm trying to create a function that converts a binary number (string) into a decimal one (int). The weird part about the code below is that when the line "//cout << index << endl;" is not commented out, it works! WHY D:?
Output when commented out:
1651929379
Output when active:
7 192 Program ended with exit code: 0
Here's the entire program:
//
// testish.cpp
// Egetskojs
//
// Created by Axel Kennedal on 2014-02-13.
// Copyright (c) 2014 Axel Kennedal. All rights reserved.
//
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int BinaryToDecimal(string & binaryString);
int main(){
string binary = "11000000";
int decimal = BinaryToDecimal(binary);
cout << decimal << endl;
return 0;
}
int BinaryToDecimal(string & binaryString){
int solution;
if (binaryString == "0") solution = 0;
if (binaryString == "1") solution = 1;
int index = binaryString.length() - 1; //The index of the last (rightmost) bit in the string
//cout << index << endl;
int currentBit = 0; //The exponent to be used when calculating the value of a bit
for (; index >= 0; index--) {
if (binaryString.at(index) == '1') {
solution += pow(2, currentBit);
}
//Else: nothing happens
currentBit++;
}
//Done!
return solution;
}
Upvotes: 1
Views: 63
Reputation: 5108
As Joachim said, your solution variable is uninitialized, so when the string is neither "0" nor "1", you may get strange behavior (e.g. integer overflows) in your += operation. I guess that the fact that it works when the output is active is due to some weird side-effect of the output instructions causing some register to contain 0, and that register being the source of the value for solution
. It might be enlightening to know what your compiler settings are for this, and to look at the assembler code for this part of your code.
You could replace:
int BinaryToDecimal(string & binaryString){
int solution;
if (binaryString == "0") solution = 0;
if (binaryString == "1") solution = 1;
...
with:
int BinaryToDecimal(string & binaryString){
int solution = 0;
...
Since the special case handling you do is elegantly handled by your loop after.
Upvotes: 0
Reputation: 409136
You have undefined behavior in the BinaryToDecimal
, because the variable solution
may be used uninitialized.
Uninitialized local variables will have indeterminate values (i.e. their values will be seemingly random).
Upvotes: 4