我如何在数组中存储二进制数?

时间:2021-07-30 20:41:41

标签: c++ arrays random binary decimal

好的,所以我一直在做这个,目的是成为加密软件的一部分,它的工作原理与 2fa 类似

 #include <iostream>
 #include <cstdio>     
 #include <cstdlib>   
 #include <ctime>    
 using namespace std;

 int main()
 {


int RGX;
int box[32];

srand (time(NULL));


RGX = rand() % 100000000 + 9999999;

cout << "Random Generated One Time HEX #:" << endl;

cout << std::hex << RGX << endl;


while(RGX!=1 || 0)
{

int m = RGX % 2;
cout << " " << m << " ";


RGX = RGX / 2;


cout << RGX << endl;



} 

return 0;
}

这是它输出的示例:

Random Generated One Time HEX #:
3ff3c70
0 1ff9e38
0 ffcf1c
0 7fe78e
0 3ff3c7
1 1ff9e3
1 ffcf1
1 7fe78
0 3ff3c
0 1ff9e
0 ffcf
1 7fe7
1 3ff3
1 1ff9
1 ffc
0 7fe
0 3ff
1 1ff
1 ff
1 7f
1 3f
1 1f
1 f
1 7
1 3
1 1


** Process exited - Return Code: 0 **

每次结果都不同,因为它是随机的,我还没有完成。但我需要知道的是如何将二进制值存储在数组中,二进制值是左边的数字。

2 个答案:

答案 0 :(得分:2)

您可以使用 std::bitset 而不是手动提取位和数组:

#include <iostream>
#include <ctime> 
#include <cstdlib>   
#include <bitset>

int main() {
    srand (time(NULL));
    int RGX = rand() % 100000000 + 9999999;

    std::cout << "Random Generated One Time HEX #: \n";
    std::cout << std::hex << RGX << "\n";
    std::bitset<32> box(RGX);
    for (int i=0;i<32;++i){
        std::cout << box[i];
    }
 
}

Possible output

Random Generated One Time HEX #: 
478ada7
11100101101101010001111000100000

<块引用>

在“while(RGX!=1 || 0)”之后的括号内没有,它使用 % 并除以 2 直到达到 1 或 0。

没有。那不是那个条件所说的。条件表示“循环 while (RGX 不等于 1) 或 0”。由于 0 在转换为 false 时始终为 bool,因此您的条件等效于 while(RGX != 1)

答案 1 :(得分:0)

您可以使用(不知道为什么要)std::bitset 来存储未打包的位集合。最好将 <random> 用于 RNG 设施。

#include <iostream>
#include <cstdlib>
#include <bitset>
#include <random>
using std::cout;

int main()
{
    std::random_device rd;
    std::uniform_int_distribution<int> dist(0, 9999999);

    unsigned RGX = dist(rd);

    cout << "Random Generated One Time HEX #:" << std::endl;

    std::bitset<32> bits {RGX}; // E.g. bits[5] would give you 5th bit
   
    cout << std::hex << RGX << " contains "<< bits << std::endl;  

    return 0;
}