在c++中将小数数组转换为8位二进制形式



我要创建一个程序(1)交换我的数组
(2)对交换后的数组执行Caesar密码替换(3)将(2)中的十进制数组转换为8位二进制

到目前为止,我已经成功地完成了前两部分,但我面临的问题是将数组从十进制格式转换为二进制格式。

这是我尝试过的代码

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void swapfrontback(int a[], int n);
int main()
{
int a[10], i, n;
cout << "enter size" << endl;
cin >> n;
if (n == 0)
{
cout << "Array is empty!n";
}
else
{
cout << "p = " << endl;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
} 
swapfrontback(a,n);

//caesar cipher

int shift = 0;
cout << "input shift: ";
cin >> shift;

int modulus = 0;
cout << "input modulus: ";
cin >> modulus;

cout << "p''=" << endl;

for (i = 0; i < n; i++)
{
a[i] = (a[i] + shift) % modulus;
cout << a[i] << endl;
}

// Function that convert Decimal to binary

int b;
b = 8;

cout<< "p'''=" << endl;

for (i = 0; i < n; i++)
{

for(int i=b-1;i>=0;i--)
{

if( a[i] & ( 1 << i ) ) cout<<1;
else cout<<0;  
}
}

return 0;

}
void swapfrontback(int a[], int n)
{
int i, temp;
for (i = 0; i < n / 2; i++)
{
temp = a[i];
a[i] = a[n - i-1];
a[n - i-1] = temp;
}

cout << "p' = '" << endl;

for (i = 0; i < n; i++)
{
cout << a[i] << endl;
}
}

的问题是,而不是转换数组的十进制从第二部分是凯撒密码到它的二进制形式,我得到000000010000000100000001。我的初始数组是

3
18
25

移位8,模26。如果有人知道如何解决这个问题,请帮助我。

嗯,似乎有一些东西可能是未来的问题(如n大于10,但是,关于你的问题,这个嵌套的for句子是错误的。

for (i = 0; i < n; i++)
{

for(int i=b-1;i>=0;i--) //here you are using the variable 'i' twice
{

if( a[i] & ( 1 << i ) ) cout<<1; //i starts at 7, which binary representation in 4 bits is 0111
else cout<<0;  
}
}

当你使用嵌套的for句子,这是一个好主意,不要重复他们的迭代变量的名字,因为他们可以相互影响,并创建讨厌的东西,如无限循环或类似的东西。尝试使用不同的变量名,以避免混淆和问题:

for(int j=b-1;j>=0;j--) //this is an example

最后,背后的想法改变一个基地10数字的二进制表示(是使用&运营商知道给定的1号位位置是1(真正的)或0(假))例如,假设你想把14其二进制形式(00001110),这个想法是为了开始&操作1号,一个继续的力量2(因为他们永远是一个数字用一个1和落后于0)1 - 1 2 - 10 4 - 100 8 - 1000,等。

所以你开始j = 1应用&操作之间,你的电话号码(在本例中14日):00000001 & 000011100是因为没有一个给定索引的数量有一个' 1 '有些共同之处,所以第一位14是0,那么你要么j乘以两个(j*=2),或改变他们的左位(j = 1<<j)向左移动你咬了一个位置,现在j = 2(00000010),和2,14是2,因为它们的第二位都是'1',所以,由于结果不是0,我们知道14的第二位是'1',算法是这样的:

int j = 128; 128 because this is the number with a '1' in the 8th bit (your 8 bit limit)
int mynumber = 14;
while(j){ // when the j value is 0, it will be the same as false
if(mynumber & j) cout<<1;
else cout<<0;
j=j>>1;
} 

希望你能理解,请确保你的数字适合8位(最大255)。

最新更新