我有二进制数,我需要:
1) 否定所有字节
2) 加 1 否定数
所以,我写了这个:
public string u2_number_plus = "1001";
public string u2_number_minus = "";
public string binToU2()
{
int length = u2_number_plus.Length;
int temp = 1;
//negate all bytes
for (int a = 0; a < length; a++)
{
if (u2_number_plus[a] == '1')
u2_number_minus += '0';
else
u2_number_minus += '1';
}
//add 1 to my new (because negate) number
for (int b = length - 1; b >= 0; b--)
{
if (u2_number_minus[b] == 0 && temp == 1)
{
u2_number_minus = u2_number_minus.Replace(u2_number_minus[b], '1');
temp = 0;
}
else if (u2_number_minus[b] == 1 && temp == 1)
{
u2_number_minus = u2_number_minus.Replace(u2_number_minus[b], '0');
temp = 1;
}
else
break;
}
return u2_number_minus;
}
我的函数 binToU2() 返回否定但不增加值。如果输入数据是 1001,我应该得到 0111,但函数只返回 0110。我哪里出错了?