lostsky25
lostsky25

Reputation: 95

Base64 implementation with bit shifting

I try to implement a base64 encoder. I have this algorithm:

while (len--)
{
    char_array_3[i++] = *(data++);

    if (i == 3)
    {
        char_array_4[0] = (char_array_3[0] & 252) >> 2; //This line.
        char_array_4[1] = ((char_array_3[0] & 3) << 4) + ((char_array_3[1] & 240) >> 4);
        char_array_4[2] = ((char_array_3[1] & 15) << 2) + ((char_array_3[2] & 192) >> 6);
        char_array_4[3] = char_array_3[2] & 63;

        for (i = 0; i < 4; i++) {
            ret += base64_chars[char_array_4[i]];
        }
        i = 0;
    }
}

Why I should do char_array_3[0] & 252? I can use only >> 2. Since ...

For instance, if I put this character H:

H -> 01001000

I can do bit shift: 01001000 >> 2 = 000100100

Or use and (&)...

252 -> 11111100

01001000 & 11111100 = 01001000 I will have the same digit...

And then need to do this: 01001000 >> 2 = 000100100

May I remove the number 252, 3, 240 etc.?

Upvotes: 0

Views: 175

Answers (1)

Slava
Slava

Reputation: 44268

May I remove the number 252, 3, 240 etc.?

No, not all of them. In case of right shift and binary mask 252, 240 and 192 they are redundant and you can remove them. But 3 15 and 63 are not redundant, as you would propagate bits that you should not to.

Upvotes: 2

Related Questions