From 1ce79f5d09f15858c5d94b4a0ed6118183fa6f07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnther=20Foidl?= Date: Mon, 20 Dec 2021 16:58:11 +0100 Subject: [PATCH] Simplified calculation of base64 encoded and decoded length For encoded length there's no need for the costly modulo operator. For decoded length we can use bit-shifts instead of costly division. --- Base64.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Base64.cpp b/Base64.cpp index 8f59178..d2f4f6c 100644 --- a/Base64.cpp +++ b/Base64.cpp @@ -94,8 +94,8 @@ int base64_decode(char * output, char * input, int inputLen) { } int base64_enc_len(int plainLen) { - int n = plainLen; - return (n + 2 - ((n + 2) % 3)) / 3 * 4; + int numWholeOrPartialInputBlocks = (sourceLength + 2) / 3; + return numWholeOrPartialInputBlocks * 4; } int base64_dec_len(char * input, int inputLen) { @@ -105,7 +105,7 @@ int base64_dec_len(char * input, int inputLen) { numEq++; } - return ((6 * inputLen) / 8) - numEq; + return (inputLen >> 2) * 3 - numEq; } inline void a3_to_a4(unsigned char * a4, unsigned char * a3) {