[英]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. 我正在使用此示例代码来帮助我完成从十进制到二进制数字的转换: http : //www.planet-source-code.com/vb/scripts/ShowCode.asp? txtCodeId=13734&lngWId =3可以将十进制转换为二进制。
I tried this out successfully for smaller numbers. 我成功尝试了较小的数量。 But when I add a number for example: 2159492075 or 2159492195. The program just outputs
0
. 但是,当我添加一个数字时,例如:2159492075或2159492195。该程序仅输出
0
。 Also I've tried an equally sized number for example 1234567899 or 2134567899 and I get a proper binary representation for the numbers. 我也尝试过使用大小相等的数字,例如1234567899或2134567899,并且得到了数字的正确二进制表示形式。 I wonder why this?
我想知道为什么吗?
Initially I thought this might have been because of defining the variables as long int: 最初,我认为这可能是因为将变量定义为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. 尝试改用
long long
类型。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.