当前位置:网站首页>Implementation of Base64 encoding / decoding in C language
Implementation of Base64 encoding / decoding in C language
2022-04-23 01:46:00 【Traceless rain】
Bse64 Is a kind of 64 An encoding algorithm that encodes binary data with printable characters .base64 When encoding data, use three 8 Bit character data is a group of , Take these three character data ASCII code , And then to 6 Bits form a group 4 New data , this 4 The new data are 6 position , So its maximum value is 2^6=64. We use 4 individual 6 Decimal number of bit data from base64 Table to get the final encoded characters .
Base64 Encoding table
| Value | Char | Value | Char | Value | Char | Value | Char |
| 0 | A | 16 | Q | 32 | g | 48 | w |
| 1 | B | 17 | R | 33 | h | 49 | x |
| 2 | C | 18 | S | 34 | i | 50 | y |
| 3 | D | 19 | T | 35 | j | 51 | z |
| 4 | E | 20 | U | 36 | k | 52 | 0 |
| 5 | F | 21 | V | 37 | l | 53 | 1 |
| 6 | G | 22 | W | 38 | m | 54 | 2 |
| 7 | H | 23 | X | 39 | n | 55 | 3 |
| 8 | I | 24 | Y | 40 | o | 56 | 4 |
| 9 | J | 25 | Z | 41 | p | 57 | 5 |
| 10 | K | 26 | a | 42 | q | 58 | 6 |
| 11 | L | 27 | b | 43 | r | 59 | 7 |
| 12 | M | 28 | c | 44 | s | 60 | 8 |
| 13 | N | 29 | d | 45 | t | 61 | 9 |
| 14 | O | 30 | e | 46 | u | 62 | + |
| 15 | P | 31 | f | 47 | v | 63 | / |
because base64 The encoding is to code before 3*8 Bit data , Decompose into 4 individual 6 A data , So after base64 The length of the encoded string is 4 Multiple . But often the length of data we encode is not 3 Multiple , That's what happened “ code ” The last digit is not 4 Multiple , such as Brisk common 5×8=40 position , With 6 A group of bits can be divided into 7 Group , such “ code ” After that 7 Characters , but base64 The encoded character length should be 4 Multiple , Obviously there's a problem here , So what to do ? The front can't be abandoned , So it's just “ Additional ” 了 , therefore Brisk after base64 The encoded length should be 8 Characters , And the first 8 The first encoded character is '=', Another example is for a single character a Conduct base64 code , Because its length is not 3 Multiple , With 3 A byte is a group. It can only be divided into one group , And then to 6 A bit is a bit. It can only be divided into two groups , So after “ code ” After that, its length is 2, but base64 The number after coding should be 4 Multiple , So its length should be 4, So add two in the back ‘=’, Because of the remainder of a number 3 There are three different results ,0、1、2, So we're doing... On a piece of data base64 After encoding, its length is :
(1) When the length of the encoded data is 3 A multiple of the ,len=strlen(str_in)/3*4;
(2) When the length of the encoded data is not 3 A multiple of the ,len=(strlen(str_in)/3+1)*4;
We use Brisk Use this example to illustrate base64 The process of coding . First of all, we use 3 A group of characters will Brisk Grouping ,Brisk By two groups :Bri and sk; Then we take out the of each byte in the two packets ASCII code ,B:66 r:114 i:105 s:115 k:107. Their corresponding binary number is B:01000010 r:01110010 i:01101001 s:01110011 k:01101011;
The first group , We use 6 Bits are a group for each 3 When bytes are grouped and then grouped, it becomes 010000 100111 001001 101001. The corresponding decimal number is 16 39 9 41, Corresponding base64 The result in the table is Q n J p;
The second group ,011100 110110 101100( Not enough 0), So the corresponding decimal number is 28 54 44, Corresponding base64 The result in the table is c 2 s, The final result is QnJpc2s=( Because the second group “ code ” The last three bytes ).
The decoding process is an inverse process , We press the encoded character 4 Characters in a group , Then compare it with base64 The table gets the corresponding decimal number , Then split and combine them , form 3 individual 8 Bit data , The decoded data is this data , Here's a c Language encoding and decoding code .
/*base64.h*/
#ifndef _BASE64_H
#define _BASE64_H
#include <stdlib.h>
#include <string.h>
unsigned char *base64_encode(unsigned char *str);
unsigned char *bae64_decode(unsigned char *code);
#endif
/*base64.c*/
#include "base64.h"
unsigned char *base64_encode(unsigned char *str)
{
long len;
long str_len;
unsigned char *res;
int i,j;
// Definition base64 Encoding table
unsigned char *base64_table="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Calculation process base64 The length of the encoded string
str_len=strlen(str);
if(str_len % 3 == 0)
len=str_len/3*4;
else
len=(str_len/3+1)*4;
res=malloc(sizeof(unsigned char)*len+1);
res[len]='\0';
// With 3 individual 8 Bit characters are encoded as a group
for(i=0,j=0;i<len-2;j+=3,i+=4)
{
res[i]=base64_table[str[j]>>2]; // Take out the first character 6 Bit and find the corresponding result character
res[i+1]=base64_table[(str[j]&0x3)<<4 | (str[j+1]>>4)]; // Align the last bit of the first character with the first bit of the second character 4 Bits and find the corresponding result character
res[i+2]=base64_table[(str[j+1]&0xf)<<2 | (str[j+2]>>6)]; // After the second character 4 Bit and the first... Of the third character 2 Bit combination and find the corresponding result character
res[i+3]=base64_table[str[j+2]&0x3f]; // After taking out the third character 6 Bit and find the result character
}
switch(str_len % 3)
{
case 1:
res[i-2]='=';
res[i-1]='=';
break;
case 2:
res[i-1]='=';
break;
}
return res;
}
unsigned char *base64_decode(unsigned char *code)
{
// according to base64 surface , Find the corresponding decimal data in characters
int table[]={0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,62,0,0,0,
63,52,53,54,55,56,57,58,
59,60,61,0,0,0,0,0,0,0,0,
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,0,0,0,0,0,0,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
};
long len;
long str_len;
unsigned char *res;
int i,j;
// Calculate the length of the decoded string
len=strlen(code);
// Judge whether there is..., after the encoded string =
if(strstr(code,"=="))
str_len=len/4*3-2;
else if(strstr(code,"="))
str_len=len/4*3-1;
else
str_len=len/4*3;
res=malloc(sizeof(unsigned char)*str_len+1);
res[str_len]='\0';
// With 4 One character is decoded as one bit
for(i=0,j=0;i < len-2;j+=3,i+=4)
{
res[j]=((unsigned char)table[code[i]])<<2 | (((unsigned char)table[code[i+1]])>>4); // Take out the first character corresponding to base64 Before the decimal number of the table 6 Bit corresponds to the second character base64 After the decimal number of the table 2 Bits are combined
res[j+1]=(((unsigned char)table[code[i+1]])<<4) | (((unsigned char)table[code[i+2]])>>2); // Take out the second character corresponding to base64 After the decimal number of the table 4 Bit corresponds to the third character bas464 After the decimal number of the table 4 Bits are combined
res[j+2]=(((unsigned char)table[code[i+2]])<<6) | ((unsigned char)table[code[i+3]]); // Take out the third character corresponding to base64 After the decimal number of the table 2 Place and number 4 Two characters to combine
}
return res;
}
/* A test program */
#include "base64.h"
#include <stdio.h>
#include <string.h>
int main(int argc,char **argv)
{
unsigned char *buf =NULL;
if(strcmp(argv[1],"-d") == 0)
{
buf = base64_decode(argv[2]);
printf("%s\n",buf);
}
else
{
buf = base64_encode(argv[1]);
printf("%s\n",buf);
}
free(buf);
return 0;
}
————————————————
Copyright notice : This paper is about CSDN Blogger 「Alen.Wang」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/qq_26093511/article/details/78836087
版权声明
本文为[Traceless rain]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230143119863.html
边栏推荐
- W801/W800/W806唯一ID/CPUID/FLASHID
- Chris LATTNER, father of llvm: the golden age of compilers
- . net unit test Part 1: common Net unit test framework?
- LSF的常用使用命令总结
- Realize the function of progress bar through layerdrawable
- How can e-procurement become a value-added function in the supply chain?
- [经验教程]支付宝余额自动转入余额宝怎么设置关闭取消支付宝余额自动转入余额宝?
- The most easy to understand service container and scope of dependency injection
- ESP32使用freeRTOS的消息队列
- 2022第六季完美童模 IPA國民賽領跑元宇宙賽道
猜你喜欢

W801 / w800 / w806 unique ID / CPUID / flashid

第六章 使用 matplotlib 绘制热力图

Dimension C China helping farmers in rural areas warms people's hearts the third stop is jiabaoguo farm

关于C4D动画如何导入Lumion

安装mysql出问题求解决

CC2541的仿真器CC Debugger使用教程
![[经验教程]支付宝余额自动转入余额宝怎么设置关闭取消支付宝余额自动转入余额宝?](/img/d5/6aa14af59144b8c99aa6a367479f6b.png)
[经验教程]支付宝余额自动转入余额宝怎么设置关闭取消支付宝余额自动转入余额宝?

Solve the problem when installing MySQL

如何“优雅”的测量系统性能

Redis实现分布式锁
随机推荐
最长公共子序列(记录路径版)
Find number (DFS)
Sqlserver data transfer to MySQL
(product resources) mingdeyang ad8488 module high performance digital X-ray FMC interface 128 analog channel high-speed ADC chip
领导/老师让填写电子excel表格文档可手机上如何编辑word/excel文件填写excel/word电子文档?
The leader / teacher asks to fill in the EXCEL form document. How to edit the word / Excel file on the mobile phone and fill in the Excel / word electronic document?
Question bank and online simulation examination for safety management personnel of hazardous chemical business units in 2022
Do447 manage user and team access
Detonate the bomb (DFS)
2022 melting welding and thermal cutting operation certificate examination question simulation examination platform operation
Is the stable currency a super opportunity to accelerate the death of the public chain or replace BTC?
J-link v9 使用技巧之虚拟串口功能
npm——配置淘宝镜像
W801/W800/W806唯一ID/CPUID/FLASHID
2022.4.22-----leetcode.396
English abbreviation of role personal attribute
Prince saves Princess (DFS)
Qingyan environment and Shenzhen Stock Exchange listing: annual revenue of 180 million and market value of 4.1 billion
W801 / w800 WiFi socket development (I) - UDP
After disk D is distributed to Disk C, what should I do if the database recovery hangs? Please answer