Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

padding in vector with zeros

my plaintext is first converted to binary text, then it should be divided into 64 bit blocks and the key has to encrypted tese blocks separately. for example, if my text has 90 bits it should be supplemented with zeros so that it has 128 bits. I do not know how to do this. here is my code:

string ifile = "filetxt.txt";
string ofile = "file2.txt";
string key = "keywordd";
vector<int> k;
vector<int> txt;
char text;
vector<int> o;
int i;
int c = 0;
int d = 1;

void f() {
    ifstream ist ("filetxt.txt");
    ofstream ost ("file2.txt");
    int a[64], i;
    while (ist >> text) {
        for(char& text : key) {
            for(i=0; i < 8; i++){
                a[i] = text%2;
                text = text/2;
            }
            for(i=i-1; i >= 0 ;i--){
                k.push_back(a[i]);
            }
        }
        if (ist) {
            for(i=0; i < 8; i++){
                a[i] = text%2;
                text = text/2;
            }
            for(i=i-1 ;i >= 0 ;i--){
                txt.push_back(a[i]);
            }
            for(int j = 0; j < 8; j++) {
                if(k[j] == txt[j]) {
                    o.push_back(c);
                } else if (k[j] != txt[j]) {
                    o.push_back(d);
                }
            }
            for(i=0; i<8; i++) {
                ost << o[i];
            }
            for(i=0; i<8; i++) {
                cout << o[i];
            }
        }
    }
    cout << endl;
    for(i=0; i<64; i++) {
        cout << k[i];
    }
    cout << endl;
    for(i=0; i<64; i++) {
        cout << txt[i];
    }
}
int main()
{
    f();
    return 0;
}

i was to do something like this:

if (txt.size()< 64){
    for(i= 0; i< 64- txt.size();i++){
        txt.push_back(c);
    }
}

i think that the problem is in the txt vector because if i want to print it i

like image 499
sonia Avatar asked Dec 04 '25 03:12

sonia


2 Answers

It's very easy:

if (txt.size()< 64)
    txt.resize(64);

This will simply pad out the vector with the default value for int, which is 0.

If you want a value other than 0 (c as your code suggests) then it's:

if (txt.size()< 64)
    txt.resize(64, c);
like image 162
Jasper Kent Avatar answered Dec 05 '25 19:12

Jasper Kent


What you want is std::vector::resize. By default it will increase the size of the vector to the size requested (if the vector is less then said size), and any elements added will be value initialized, which for an int means zero initialized. That gives you

if (txt.size() % 64 != 0)
    txt.resize(txt.size() + (64 - (txt.size() % 64)));

Also note that 64 int's is not 64 bits. An int has to have at least a size of 16 bits meaning 64 of them will be at least 512 bits. If you actually need to have 64 bit chunks, you should be using a std::uint64_t for the bit chunks (or something like it)

like image 42
NathanOliver Avatar answered Dec 05 '25 17:12

NathanOliver