我試圖將矢量的位轉換爲十進制整數。我的程序是一個可變的線性反饋移位寄存器。首先它向用戶詢問LFSR的初始序列的長度,然後它要求序列本身和位的位置進行着色。所以如果我輸入序列長度爲4,比特序列爲1110,多項式爲20,密鑰爲0111100,它存儲在向量keyReg中,我嘗試使用for條件將其轉換爲十進制數:將矢量的位轉換爲十進制整數
for (unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(2^i);
cout << key << "\n";
}
}
但是,這不會產生相當於0111100的正確十進制數。該怎麼辦? 以下是完整的程序:
#include <iostream> //Standard library.
#include <boost/dynamic_bitset.hpp> //Library for 10 handling.
#include <vector> //Variable size array.
#include <algorithm> //We use sorting from it.
using namespace std;
int main()
{
int y = 0;
int turnCount = 0;
int count1 = 0, count0 = 0;
int xx = 0;
int polyLoc;
int key = 0;
boost::dynamic_bitset<> inpSeq(5);
boost::dynamic_bitset<> operSeq(5);
boost::dynamic_bitset<> bit(5);
vector <int> xorArray;
vector <int> keyReg;
cout << "What is the legnth of the sequence?";
cin >> xx;
inpSeq.resize(xx);
operSeq.resize(xx);
bit.resize(xx);
cout << "Enter a bit sequence: \n";
cin >> inpSeq;
int seq_end = inpSeq.size() - 1;
cout << "Enter polynomial:";
cin >> polyLoc;
while(polyLoc>0)
{
xorArray.push_back(polyLoc%10);
polyLoc/=10;
}
sort(xorArray.rbegin(), xorArray.rend());
cout << "\n";
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
do {
for (unsigned int r = 1; r < xorArray.size(); r++)
{
bit[seq_end] = operSeq[x];
y = xorArray[r];
bit[seq_end] = bit[seq_end]^operSeq[y];
}
operSeq >>= 1;
operSeq[seq_end] = bit[seq_end];
keyReg.push_back(operSeq[0]);
turnCount ++;
cout << operSeq << "\n";
}
while ((operSeq != inpSeq) && (turnCount < 1024));
cout << "Generated key is: ";
for (unsigned int k = 0; k < keyReg.size(); k++)
{
cout << keyReg[k];
}
cout << "\n";
cout << "Bit 1 positions: ";
for (unsigned int g = 0; g < xorArray.size(); g++)
{
cout << xorArray[g];
}
cout << "\n";
cout << "Key length is: " << keyReg.size();
cout << "\n";
for (unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
count1++;
}
else {
count0++;
}
}
cout << "Number of 0's: " << count0 << "\n";
cout << "Number of 1's: " << count1 << "\n";
if (keyReg.size()%2 ==0)
{
cout << "key length is even. \n";
if (count1==count0)
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
else
{
cout << "key length is odd. \n";
if ((count1==count0+1) || (count0==count1+1))
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
for (unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(2^i);
cout << key << "\n";
}
}
cout << "Key is " << key << "\n";
cin.get();
}
好吧,但是(1 << i)對於我的力量怎麼樣? –
@MooingDuck嗯,他在開始時提取了相關的代碼示例,有時我使用電子表格,人們傾向於使用'^'來取冪。 – luk32
@MohamedAhmed我添加了它爲什麼有效的部分。 – luk32