From 4769890d4edb81ed6930875e9a0d3eaf0788a06d Mon Sep 17 00:00:00 2001 From: "Steve K. Chiu" Date: Sat, 12 Mar 2016 15:42:52 +0800 Subject: [PATCH] Fix calculation of outLength The order of integer arithmetic is important, the original code fail to calculate the length correctly, e.g. inLength 20 for base64Encode should output 28, not 30. It is fixed and simplified with this commit. --- cocos/base/base64.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/base/base64.cpp b/cocos/base/base64.cpp index 5e7b7ef0de..46990b3539 100644 --- a/cocos/base/base64.cpp +++ b/cocos/base/base64.cpp @@ -142,7 +142,7 @@ int base64Decode(const unsigned char *in, unsigned int inLength, unsigned char * unsigned int outLength = 0; //should be enough to store 6-bit buffers in 8-bit buffers - *out = (unsigned char*)malloc(inLength * 3.0f / 4.0f + 1); + *out = (unsigned char*)malloc(inLength / 4 * 3 + 1); if( *out ) { int ret = _base64Decode(in, inLength, *out, &outLength); @@ -160,7 +160,7 @@ int base64Decode(const unsigned char *in, unsigned int inLength, unsigned char * } int base64Encode(const unsigned char *in, unsigned int inLength, char **out) { - unsigned int outLength = inLength * 4 / 3 + (inLength % 3 > 0 ? 4 : 0); + unsigned int outLength = (inLength + 2) / 3 * 4; //should be enough to store 8-bit buffers in 6-bit buffers *out = (char*)malloc(outLength+1);