-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBase32Encoder.cpp
65 lines (55 loc) · 1.82 KB
/
Base32Encoder.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/***************************************************************************************
* Title: Base32 Encoding In C++
* Author: MadeBits 2018
* Project: cpp-base32
* Date: 07.11.2018
* Availability: https://github.com/madebits/cpp-base32
*
***************************************************************************************/
#include "Base32Encoder.h"
int Base32Encoder::GetEncode32Length(int bytes) {
int bits = bytes * 8;
int length = bits / 5;
if((bits % 5) > 0) {
length++;
}
return length;
}
static bool Encode32Block(unsigned const char* in5, unsigned char* out8) {
// pack 5 bytes
unsigned long long int buffer = 0;
for(int i = 0; i < 5; i++) {
if(i != 0) {
buffer = (buffer << 8);
}
buffer = buffer | in5[i];
}
// output 8 bytes
for(int j = 7; j >= 0; j--) {
buffer = buffer << (24 + (7 - j) * 5);
buffer = buffer >> (24 + (7 - j) * 5);
unsigned char c = (unsigned char)(buffer >> (j * 5));
// self check
if(c >= 32) return false;
out8[7 - j] = c;
}
return true;
}
bool Base32Encoder::Encode32(const unsigned char* in, int inLen, unsigned char* out) {
if((in == 0) || (inLen <= 0) || (out == 0)) return false;
int d = inLen / 5;
int r = inLen % 5;
unsigned char outBuff[8];
for(int j = 0; j < d; j++) {
if(!Encode32Block(&in[j * 5], &outBuff[0])) return false;
memmove(&out[j * 8], &outBuff[0], sizeof(unsigned char) * 8);
}
unsigned char padd[5];
memset(padd, 0, sizeof(unsigned char) * 5);
for(int i = 0; i < r; i++) {
padd[i] = in[inLen - r + i];
}
if(!Encode32Block(&padd[0], &outBuff[0])) return false;
memmove(&out[d * 8], &outBuff[0], sizeof(unsigned char) * GetEncode32Length(r));
return true;
}