如此 dbg 调试日志所示,string1 = '0' <repeats 28 times>, "1000"
在 intToBinary(num1, string1) 函数调用之后打印。但随后在下一条指令 intToBinary(num2, string2) 被调用。如您所见,不同的参数被传递给 intToBinary 函数。第二次使用不同的变量调用函数时,变量怎么会string1
受到影响?在日志中,它说第一个字符从 0 变为(或?)。\
\0
如有必要,这是该功能的 pastebin。http://pastebin.com/EsQNMjej
void intToBinary(int num, char* string)
{
string[32] = '\0';
int i,j;
int temp = num;
// is num negative?
int isNegative = num < 0 ? 1 : 0;
//negate all bits and add 1 (two complements)
if(isNegative)
{
temp = -1 * temp; //absolute value
//In order to get the negative number in
// 2's complement you can either negate and
// increment, or decrement by 1 and negate.
//In this function, temp gets negated after
//the conversion to string
--temp;
}
//Write binary of positive num to string
for(i = 0, j = 31; i < 32; i++,j--)
{
if(pow(2,j) <= temp)
{
//Temp is decreased when the bit is 1
temp = temp - pow(2, j);
string[i] = '1';
}
else
{
//Nothing happens to temp when the bit is 0
string[i] = '0';
}
}
if(isNegative)
{
for(i = 0; i < 32; i++)
{
//negate bits
string[i] = string[i] == '1' ? '0' : '1';
}
}
}
我只是不明白这里发生了什么。我尝试切换两个函数调用的顺序,所以它变成了以下
intToBinary(num2, string2);
intToBinary(num1, string1);
神奇的是,第一个字节保持不变'0'
,这就是我想要的。但现在我只想知道为什么这首先会改变......