c++algorithm

How do I predict the required size of a Base32 Decode output?


I have a std::string that is base32 encoded and I have a function that decodes it. The function takes a char* input, a char* destination and a length. How do I know what length I will need for the destination? I need to know what array to allocate for the destination. How do I determine the size?


Solution

  • Base32 allows to encode each 5 bits ( as 32 = 2^5 ) using single character.

    It means that you need output buffer size for encoding:

    dst_size = src_size * 8 / 5 (1.6 times larger)
    

    But as base32 string length must be multiple of 40 bits:

    dst_size = (src_size * 8 + 4) / 5
    

    Thus, for decoding (base32->binary) required buffer size is accordingly

    dst_size = ceil( src_size / 1.6 )