hi, i have written this code for converting from base 10 to base 2 but it dose not work for numbers having more than 3 digits.(like 1231) if anyone can help me?
thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
usingnamespace std;
#include<math.h>
int main()
{ int num;
cout<<"enter a number"<<endl;
cin>>num;
int i=0;
unsignedlong k=0;
while(num>=1){
k+=(num%2)*powf(10,i);
num/=2;
i++;}
cout<<"your number in 2 base "<<k<<endl;
return 0;}
It sounds like your unsigned long is 32 bits, which has room for only 10 digits (when the digits are 0 and 1). So you're overflowing the size of unsigned long.
Rather than creating a new number, why not put the results into a string? That way you don't have to worry about the size. Just peel off the least significant bit at each iteration of the loop and append it to a string. When you're done, reverse the string to get it in the right order.