Frage

I am implementing DES (with EBC) as part of school work. I am using boolean arrays bool[64] from <stdbool.h> for the blocks. The array uses 1 byte for each bit (I learned this the hard way when I tried memcpy for 64bits=8 bytes instead of 64 bytes). Anyway, how to fread into the bit array? Right now, I'm reading into an unsigned long and converting it. Like below:

unsigned long buf;
bool I[64], O[64];
int ctr = 0;
while((ctr = fread(&buf, 1, 8, fin))>0) {
    dectobin(buf, I);
    encrypt(I, O);
    buf=bintodec(O);
    fwrite(&buf, 8, 1, fout);
    buf = 0;
}

The functions are:

void dectobin(unsigned long dec, bool bin[64]) 
{
    int i;
    for(i = 0; i< 64; i++)
        bin[i] = (dec>>(63-i)) & 1;
}

unsigned long bintodec(bool bin[64])
{
    unsigned long dec = 0;
    int i;
    for(i = 0; i < 64; i++) {
        dec <<= 1;
        dec |= (int)(bin[i]);
    }
    return dec;
}

Is there a better way to do this?

War es hilfreich?

Lösung

You can´t directly fread bits in a bool array
(you would have to read bytes and assign each 8 bits of each byte manually).

Another solution, which consumes less memory too:
An array of 8 chars.
Can be fread-ed directly, and the bits are accessed by binary Or/And & |
If you have a char c and a bit number n between 0 and 7:
Set bit n in c to 1:

c |= 1<<n;

Set bit n in c to 0:

c &= ~(1<<n);

Check if bit n in c is 1:

if(c & (1<<n))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top