简体   繁体   中英

Changing from decimal to binary

I'm using this sample code to help me accomplish decimal to binary number conversion : http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=13734&lngWId=3 to convert from decimal to binary.

I tried this out successfully for smaller numbers. But when I add a number for example: 2159492075 or 2159492195. The program just outputs 0 . Also I've tried an equally sized number for example 1234567899 or 2134567899 and I get a proper binary representation for the numbers. I wonder why this?

Initially I thought this might have been because of defining the variables as long int:

long int dec,k=0,i=0,j=0,n,remainder,result[100];

But on digging further, I don't think that is an issue. Could someone suggest what I might be doing incorrectly?

Try using long long type instead. Your problem may be not more than overflow.

void convert(long long n, int arr[100], int & i)
{
   i = 0;
   do
   {
       arr[i++] = n % 2;
       n /= 2;
   } while (n);
   for (int j = 0; j <= i / 2; ++j) swap(arr[j], arr[i - j - 1]);
}

Usage:

int sz, my_arr[100];
convert(2013, my_arr, sz);
for (int i = 0; i < sz; ++i) cout << my_arr[i];
cout << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM