Calculate size for Base 64 decoded message

I have a BASE64 encoding string:

static const unsigned char base64_test_enc[] =
    "VGVzdCBzdHJpbmcgZm9yIGEgc3RhY2tvdmVyZmxvdy5jb20gcXVlc3Rpb24=";

It does not have CRLF-72 characters.

How to calculate the length of a decoded message?

+4
source share
2 answers

Well, base64 represents 3 bytes of 4 characters ... so for starters you just need to divide by 4 and multiply by 3.

Then you need to consider padding :

  • If the text ends with "==", you need to subtract 2 bytes (since the last group of 4 characters represents only 1 byte)
  • If the text ends only "=", you need to subtract 1 byte (since the last group of 4 characters represents 2 bytes)
  • , ( 4 3 )
+13

64 4 3 . , .

, :

  • ==
  • 3 =
  • , , , 3 .

, 4, 3 , , .


C ( C, , ):

size_t encoded_base64_bytes(const char *input)
{
    size_t len, padlen;
    char *last, *first_pad;

    len = strlen(input);

    if (len == 0) return 0;

    last = input + len - 4;
    first_pad = strchr(last, '=');
    padlen = first_pad == null ? 0 : last - first_pad;
    return (len / 4) * 3 - padlen;
}

, , 64.


, , 0 , .

+3

Source: https://habr.com/ru/post/1622334/


All Articles