pg1989
pg1989

Reputation: 1010

What exactly do these 3 lines of C code do?

I've been trying to parse them for a couple days, and I can't quite grok it. Here they are:

int left = S->buflen >> 3;
int fill = 64 - left;
if(left && (((datalen >> 3) & 0x3F) >= (unsigned)fill)){
   some code here
}

If it helps, this is in the reference implementation of the SHA-3 candidate BLAKE256.

Upvotes: 0

Views: 253

Answers (2)

Adam Mihalcin
Adam Mihalcin

Reputation: 14458

An alternative without bitops might help clear up the meaning:

int left = S->buflen / 8;
int fill = 64 - left;
if (left != 0) {
    int tmp = datalen / 8;
    if ((tmp % 64) >= (unsigned)fill) {
        /* Some code here */
    }
}

This of course assumes that buflen and datalen are nonnegative, since the right shift operator has platform-dependent behavior for negative numbers.

Upvotes: 6

Tommy
Tommy

Reputation: 100602

int left = S->buflen >> 3;

Get the number of bytes left, assuming buflen is a measurement in bits.

int fill = 64 - left;

Get the number of bytes that you'll therefore need to append to round up to a multiple of 64. Note that if S->buflen is 0 you'll end up appending an entire 64 bytes when you needn't append any, so...

if(left && (((datalen >> 3) & 0x3F) >= (unsigned)fill)){
   some code here
}

... do the some code here only if there were some bits left and datalen, converted from bits to bytes, mod 64 is at least equal to the number of extra bytes you'd need to write. Presumably because datalen is the maximum output size?

Upvotes: 1

Related Questions