@StefanL38
I tried to write without a library as a brain teaser, but I may has bad sense. ![]()
Encode / Decode Base32 using a predefined fixed length C-string buffer.
Sorry, It's tested in Arduino Nano...
#define MAX_STRING_LENGTH 50 // Must multiple of 5
/* RAM consumes bytes about 2.6 times this value and additional few bytes */
// Must set to length of an array of both string buffer
#define RAWSTR_BUFFER_BYTES (MAX_STRING_LENGTH + 1)
#define BASE32_BUFFER_BYTES (MAX_STRING_LENGTH / 5 * 8 + 1)
char rawstr[RAWSTR_BUFFER_BYTES];
char base32[BASE32_BUFFER_BYTES];
void setup() {
Serial.begin(9600);
strlcpy_PF(rawstr, PSTR("Arduino Forum"), sizeof(rawstr));
encodeBase32(base32, rawstr);
Serial.println(base32);
strlcpy_PF(base32, PSTR("KRUGS4ZANVSXG43BM5SSA53BOMQGIZLDN5SGKZBAMZZG63JAIJQXGZJTGI======"), sizeof(base32));
decodeBase32(rawstr, base32);
Serial.println(rawstr);
}
void loop() {
}
void encodeBase32(char* b32, const char* str) {
unsigned char fin = 0, bits;
unsigned int bcnt = 0, scnt = 0;
while (bcnt < BASE32_BUFFER_BYTES) {
bits = *(str + scnt);
if (!bits) break;
fin = (fin + 5) & 7;
if (fin >= 5) {
bits >>= 8 - fin;
} else {
bits <<= fin;
bits |= *(str + ++scnt) >> (8 - fin);
}
bits &= ~0xE0;
bits += bits < 26 ? 0x41 : 0x18;
*(b32 + bcnt++) = bits;
}
for (scnt = 8; scnt < bcnt; scnt += 8);
while (bcnt < scnt) *(b32 + bcnt++) = '=';
while (bcnt < BASE32_BUFFER_BYTES) *(b32 + bcnt++) = 0;
}
void decodeBase32(char* str, const char* b32) {
unsigned char fin = 0, bits;
unsigned int scnt = 0, bcnt = 0, buff = 0;
while (bcnt < BASE32_BUFFER_BYTES) {
bits = *(b32 + bcnt++);
if (!bits || bits == '=') break;
bits -= bits > 0x40 ? 0x41 : 0x18;
buff <<= 5;
buff |= bits;
fin += 5;
if (fin >= 8) {
fin -= 8;
*(str + scnt++) = 0xFF & (buff >> fin);
}
}
while (scnt < RAWSTR_BUFFER_BYTES) *(str + scnt++) = 0;
}
There is no error handling during decoding. ![]()
Lowercase Base32 is not accepted.
If you need it, you can add it yourself. ![]()