When i write this code to convert binary to decimal , I am getting the 1000 for 1000 as input instead of 8. Can someone help ?
’
#include
using namespace std;
int main() {
int number,two_power=1,answer=0;
cin>>number;
for(;number>0;two_power=two_power*2,number=number>>1){
if(number&1){
answer=answer+two_power;
}
}
cout<<answer;
return 0;
}
Binary to decimal code
Suppose number = 8 , then ur code will run for (1000) and only for set bit 1 in (1000) it will two_power(=8) to answer , and you will get 8 as answer which is same as input number . So, you can see you are computing same number
For computing decimal number from binary system , you have to take input as a string and then ur code will work for sure ! . Just change the data type of number to string and give input as binary string , you will get ur answer .
So the below code for better understanding
https://ide.codingblocks.com/s/41142
I think you misunderstood. I gave number=1000, not number =8.
I actually got what i was doing wrong. I was doing a right shift of 1000 i was getting 500. But i needed 0100 . It was dividing the number by 2 as such . But i just wanted to move the bits one towards the right. So instead of number>>1 , i gave number %10 and it went fine.
Thanks for your help.