MCPcopy Create free account
hub / github.com/KaisenAmin/c_std / encoding_base32_encode

Function encoding_base32_encode

encoding/encoding.c:998–1040  ·  view source on GitHub ↗

* @brief Encodes binary data into Base32 format. * * This function encodes a given input string into Base32 format. Base32 encoding * uses 32 characters to represent binary data. The output is padded with `=` characters * if necessary to ensure the encoded string length is a multiple of 8. * * @param input Pointer to the input binary data. * @param length Length of the input data. * *

Source from the content-addressed store, hash-verified

996 }
997
998 unsigned char* result = (unsigned char*) malloc(data_len * 5 / 8 + 1);
999 if (!result) {
1000 ENCODING_LOG("[encoding_base32_decode] Error: Memory allocation failed.");
1001 return NULL;
1002 }
1003
1004 size_t j = 0;
1005 unsigned int bits = 0;
1006 int nbits = 0;
1007 for (size_t i = 0; i < data_len; ++i) {
1008 int v = decode_char((unsigned char)toupper((unsigned char)input[i]));
1009 if (v < 0) {
1010 ENCODING_LOG("[encoding_base32_decode] Error: invalid character.");
1011 free(result);
1012 return NULL;
1013 }
1014 bits = (bits << 5) | (unsigned int)v;
1015 nbits += 5;
1016 if (nbits >= 8) {
1017 nbits -= 8;
1018 result[j++] = (unsigned char)(bits >> nbits);
1019 bits &= (1u << nbits) - 1u;
1020 }
1021 }
1022
1023 result[j] = '\0';
1024 if (out_len) {
1025 *out_len = j;
1026 }
1027 ENCODING_LOG("[encoding_base32_decode] Decoding completed successfully.");
1028 return (char*)result;
1029}
1030
1031
1032/**
1033 * @brief Decodes a Base32 encoded string back to binary data.
1034 *
1035 * Back-compat wrapper over `encoding_base32_decode_ex` that discards the decoded
1036 * length. Use `encoding_base32_decode_ex` for binary payloads. Padding is
1037 * optional and either letter case is accepted.
1038 *
1039 * @param input Pointer to the Base32 encoded input string.
1040 * @param length Length of the Base32 encoded string.
1041 * @return A dynamically allocated buffer containing the decoded binary data.
1042 * Returns NULL if an error occurs (e.g., memory allocation failure, invalid input length).
1043 *

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected