我的方法是在int数组的每个元素中设置位。虽然程序适用于字符串str =“11111 ... 111”(所有位都是1)的情况但是,如果字符串str =“100 ... 000”(63个零数字)(第一个) bit是1,其余的是0)问题出现了,我的int数组是{0,0,0,1}它必须是{0,0,1,0}请给我一个解决方案,我的代码,如果你的想法更好,告诉我,我可以尽快解决问题。
int arr[4]={0};
void convert(string str)
{
int length = str.length();
for (int i = length - 1; i >= 0; i--)
{
if (str[i] == '1')
{
int pos = 3 - i / 32;
int k;
k = (length - i - 1) % 31;
//if (i == 0)
//{
//pos = 2- length/32;
//}
arr[pos] = (1 << k) | arr[pos];
}
}
}
如果字符串有1000 ... 00(32 0个数字),则int数组必须为{0,0,1,0}如果字符串有1000 ... 00(63 0个数字),则int数组必须为是{0,1,0,0}
所以我找到了解决自己问题的方法。请帮我测试我的代码,然后让我知道是否有任何测试用例出错。谢谢。
class QInt
{
private:
int Data[4];
public:
QInt(){
for (int i = 0; i < 4; i++)
{
Data[i] = 0;
}
}
QInt QInt::StrBinToQInt(string str)
{
QInt temp=QInt();
str = creString128(str);
cout << str.length() << endl;
cout << str << endl;
for (int i = 127; i >= 0; i--)
{
int pos;
if (str[i] == '1')
{
pos = i / 32;
int k = (127-i) % 32;
if (i % 32 == 0)
{
pos--;
k = 0;
}
if (str[0] == '1')
{
pos = 0;
k = 30;
}
temp.Data[pos] = (1 << k) | temp.Data[pos];
}
}
return temp;
}
};
string creString(int n)
{
string temp;
for (int i = 0; i < n; i++)
{
temp += '0';
}
return temp;
}
string creString128(string bin)
{
string corrBin = creString(128 - bin.length());
corrBin += bin;
return corrBin;
}