---
# System prepended metadata

title: 12784 - Base64 Encoding

---

# 12784 - Base64 Encoding

> author: Rhino
###### tags: 

---


## brief
注意
- std::string這種class是使用[HW11420 - Implement a vector 1](https://hackmd.io/VIWV35nVQZmJj2UOVqn6gg?view)所模擬的size和capacity來動態維護object。
- 所以只能寫成==temp_1_str **<<** ???== 或者==temp_1_str = temp_1_str **+** ???==，而不能用==temp_1_str[!!**錯誤**!!]==，因為會戳到不對的記憶體位置。
## Solution 0
```cpp
#include "function.h"
#include <string>
#include <cstring>

void Base64Codec::encode() {
	encoded = true;

	int original_str_len = code_str.length();//數ㄕㄨˇ字元個數。Mano = 4。
	int original_str_len_backup = original_str_len;//備份
	original_str_len *= 8;//轉換成binary後的數字個數，如果是Mano，original_str_len = 32，但original_str_len_backup=4。
	int remainder = original_str_len % 6;//如果是32，會餘2，所以要補6-2=4個零。
	int num_of_0_to_add = remainder == 0 ? 0 : (6 - remainder);//把要補"4"個零的"4"存起來

	std::string temp_1_str;
	for (int i = 0; i < original_str_len_backup; i++) {
		int now_char_in_dec = (int)code_str[i];//如果code_str[0]=M，就把77存進裡面

		for (int j = 7; j >= 0; j--)
			temp_1_str = temp_1_str + std::to_string((now_char_in_dec & 1 << j) != 0 ? 1 : 0);//to_string: 把數字轉換成char。//
	}
	for (int i = 0; i < num_of_0_to_add; i++) 
		temp_1_str = temp_1_str + std::to_string(0);



	std::string temp_2_str;
	int count_group = (original_str_len + num_of_0_to_add) / 6;
	for (int i = 0; i < count_group; i++) {
		int this_group_in_dec = 0;

		for (int j = i * 6; j < (i + 1) * 6; j++) {
			this_group_in_dec = this_group_in_dec << 1;
			this_group_in_dec += temp_1_str[j] - '0';
		}
		
		temp_2_str = temp_2_str + encodeCharacter(this_group_in_dec);
	}
	
	for (int i = 0; i < num_of_0_to_add / 2; i++) temp_2_str = temp_2_str + '=';

	code_str = temp_2_str;
}

// By Rhino
```

## Solution 1
```cpp
#include "function.h"
#include <sstream>

void Base64Codec::encode() {
    stringstream st(code_str);
    int state = 0;
    char prev = 0;
    char ch = 0;
    
    code_str.clear();
    
    while (!st.get(ch).eof()) {
        code_str.push_back(encodeCharacter((ch >> (2 * (state + 1))) + prev));
        
        prev = 0;
        for (char i = 0; i < 2 * (state + 1); i++) {
            prev += ch & (1 << i);
        }
        prev = prev << (6 - (2 * (state + 1)));
        
        if (state == 2) {
            code_str.push_back(encodeCharacter(prev));
            prev = 0;
        }
        
        state = (state + 1) % 3;
    }
    
    if (state) {
        code_str.push_back(encodeCharacter(prev));
        code_str.append(3 - state, '=');
    }
    
    encoded = true;
}

// By koihia
```
## Reference