mercredi 27 mai 2020

Displaying 1024 bit binary number in base 10 c++

I'll try explaining my problem to the best of my ability. To start off, here's my code for a program I wrote that generates an array of n length, where each element is either a 1 or a 0. The next method takes in an array made from the first method and formats it into a binary number that can be printed to the console.

#include "bigNum.h"
#include <iostream>
#include <cstdlib>

short* genArr(int bits)
{
        static short *numArr = new short[bits];
        srand(time(0));
        int i;
        for (i = 0; i<bits; i++) {
                numArr[i] = rand() % 2;
        }
        return numArr;
}

void formatNum(short arr[], int size) {
        int i;
        for (i = 0; i<size; ++i) {
                std::cout<<arr[i];
        }
        std::cout<<"\n";
}

The main reason why I created this program is to generate large random numbers to the order of 1024 bits and beyond. I don't think a simple binary to int conversion will work because the size of my binary number is not constant, and it can clearly be larger than 64 bits.

For example, if I generate a 1024 bit binary number, it prints to the console:

./test 1024
00100110110011111111000111011111001001010001110111011001100010110010110010111000101101011011000100101101110110110100001000110100110110000011010000000101110110101010011010                     01101111010001000100100100011001111110010110011101101110111011111100101110000110000011001110101011010101101110000001000111101101000010011100000010010000110001111111010110                         11101001111110011100000110111010100001010101010101101110101000111101001011110000100010010111100000000110001100110011010000100000001110100011000000001010000100111000010111                         00000000101001000100010001100000000101111011001011011111001001011000111001101000011100000100101001001001101001000110110110100101011111001100100110001010100111000111101011                         00110010000111111101101010000011000001001110010100111010001000101111010001010000111011011101011110010010001000111011100010110101110110010100110111011011110101010011011001                         10011101001010111101000100011100101011101000110000001001000110100001011101010010011111001011011010011111110110011111011100001011010101110111111100001111100101000010000001 

EDIT: sorry, I can't remove the long tabs. I think it was due to a copy/paste formatting error.

What I want to do is to convert this long binary number into a string that displays the base 10 representation of this. I couldn't find similar problems online, so I'm resorting to posting a question here. I hope I described my problem thoroughly.




Aucun commentaire:

Enregistrer un commentaire