hi3516a-base64 encoding analysis

Preface

Base64 is one of the most common encoding methods used to transmit 8Bit bytecode on the network. Base64 is a method of representing binary data based on 64 printable characters. I saw two articles on the Internet that summarized well, you can refer to the following two articles.
https://www.cnblogs.com/libin-1/p/6165485.html
https://www.cnblogs.com/antineutrino/p/3756106.html
Selfless sharing, start with me!

C language source code

Base64 encoding index table:
Insert picture description here

//char *in, const int in_len为输入的数据,char *out, int out_len为依据base64转换后的数据
void base64_encode(char *in, const int in_len, char *out, int out_len)
{
	static const char *codes ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	int base64_len = 4 * ((in_len+2)/3);
	//把输入的长度加2,除以3后取整,再乘以4,得到编码后的数据长度,例如5个字节编码后是8个字节;加以2取整是为了包括多出来1个字节和2个字节的情况
	char *p = out;
	int times = in_len / 3;
	int i;
	
	out_len=base64_len;
	for(i=0; i<times; ++i)    //输入长度刚好是3的倍数
	{
		*p++ = codes[(in[0] >> 2) & 0x3f];//第一字节右移两位,去掉低2位,高2位补零
		*p++ = codes[((in[0] << 4) & 0x30) + ((in[1] >> 4) & 0xf)];//源第一字节低2位 + 源第2字节高4位
		*p++ = codes[((in[1] << 2) & 0x3c) + ((in[2] >> 6) & 0x3)];//第二个字节去掉高4位并左移两位(得高6位),第三个字节右移6位并去掉高6位(得低2位),相加
		*p++ = codes[in[2] & 0x3f]; //源第三字节去掉高2位
		in += 3; //转完3个字节,加3
	}
	if(times * 3 + 1 == in_len) //输入长度是3个倍数多一位
	{
		*p++ = codes[(in[0] >> 2) & 0x3f];
		*p++ = codes[((in[0] << 4) & 0x30) + ((in[1] >> 4) & 0xf)];
		*p++ = '=';   //补齐=
		*p++ = '=';  //补齐=
	}
	if(times * 3 + 2 == in_len) //输入长度是3个倍数多两位
	{
		*p++ = codes[(in[0] >> 2) & 0x3f];
		*p++ = codes[((in[0] << 4) & 0x30) + ((in[1] >> 4) & 0xf)];
		*p++ = codes[((in[1] << 2) & 0x3c)];
		*p++ = '='; //补齐=
	}
	*p = 0;
}

Guess you like

Origin blog.csdn.net/u014470361/article/details/89381398