ASCII码对照表(Base64编码)

1🎈ASCII码对照表(255个ascii字符汇总)🎈
2🎈ASCII码对照表(Unicode 字符集列表)🎈
3🎈ASCII码对照表(emoji表情符号)🎈
4🎈ASCII码对照表(Python代码实现打印)🎈
5🎈ASCII码对照表(ANSI、UTF8、Unicode编码互转)🎈
6🎈ASCII码对照表(HTML颜色代码表)🎈
7🎈ASCII码对照表(Base64编码)🎈
8🎈ASCII码对照表(键盘键位图)🎈

目录

1、Base64原理

2、Base64的Python代码实现

3、Base64的C++代码实现

后续

Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。可查看RFC2045~RFC2049,上面有MIME的详细规范。

  • 1、Base64原理

Base64是一种基于64个可打印字符来表示二进制数据的表示方法。base64要求将每三个8bits字节转换为四个6bit的字节(3 * 8 = 4 * 6 = 24),然后将转换后的6bit往高位添加2个0,组成4个8bit的字节,再根据这4个8bit字节的十进制在索引表中查找对应的值,此时得到的结果就是Base64值。理论上,转换后的字符串的长度要比原来的字符串长度长1/3。

如果数据字节数不是3的倍数,就不能精确地划分6位的块,此时需要在原数据后添加1个或2个零值字节,使其字节数为3的倍数,然后在编码后的字符串后添加1个或2个‘=’,表示零值字节。

Base64 是一种基于 64 个可打印字符来表示二进制数据的表示方法,由于 2^6=64,所以每 6 个比特为一个单元,对应某个可打印字符。

Base64 常用于在通常处理文本数据的场合,表示、传输、存储一些二进制数据,包括 MIME 的电子邮件及 XML 的一些复杂数据。

Base64 编码要求把 3 个 8 位字节(3*8=24)转化为 4 个 6 位的字节(4*6=24),之后在 6 位的前面补两个 0,形成 8 位一个字节的形式。 如果剩下的字符不足 3 个字节,则用 0 填充,输出字符使用 =,因此编码后输出的文本末尾可能会出现 1 或 2 个 =。

为了保证所输出的编码位可读字符,Base64 制定了一个编码表,以便进行统一转换。编码表的大小为 2^6=64,这也是 Base64 名称的由来。

在 Base64 中的可打印字符包括字母 A-Za-z、数字 0-9,这样共有 62 个字符,此外两个可打印符号在不同的系统中而不同。

  • Base64的变种

一种用于URL的改进Base64编码,它在末尾填充'='号,并将标准Base64中的“+”和“/”分别改成了“-”和“_”,这样就免去了在URL编解码和数据库存储时所要作的转换。

另有一种用于正则表达式的改进Base64变种,它将“+”和“/”改成了“!”和“-”。

  • Base64 Alphabet

索引

对应字符

索引

对应字符

索引

对应字符

索引

对应字符

0

A

17

R

34

i

51

z

1

B

18

S

35

j

52

0

2

C

19

T

36

k

53

1

3

D

20

U

37

l

54

2

4

E

21

V

38

m

55

3

5

F

22

W

39

n

56

4

6

G

23

X

40

o

57

5

7

H

24

Y

41

p

58

6

8

I

25

Z

42

q

59

7

9

J

26

a

43

r

60

8

10

K

27

b

44

s

61

9

11

L

28

c

45

t

62

+

12

M

29

d

46

u

63

/

13

N

30

e

47

v

14

O

31

f

48

w

15

P

32

g

49

x

16

Q

33

h

50

y

  • 2、Base64的Python代码实现

(1)字符串的base64实现: 

import base64

str = 'hello world!'.encode()#默认以utf8编码

#base64编码
res = base64.b64encode(str)
print(res.decode())#默认以utf8解码

#base64解码
res = base64.b64decode(res)
print(res.decode())#默认以utf8解码

运行结果如下: 

 (2)图片文件的base64实现:

#image转base64
import base64
with open(r'd:\test.jpg', "rb") as f:
    base64_data = base64.b64encode(f.read())
    print(base64_data)

    file=open(r'd:\test.jpg.txt','wb')
    file.write('data:image/jpg:base64,'.encode('utf-8'))
    file.write(base64_data)
    file.close()
#base64转image
import base64
with open(r"d:\test.jpg.txt","rb") as f:
    header = 'data:image/jpg:base64,'
    imgdata = base64.b64decode(f.read()[len(header):])
    file = open(r'd:\test_decrypt.jpg','wb')
    file.write(imgdata)
    file.close()    

 运行结果如下:

 在网页中使用图片base64字符串:

Base64 在CSS中的使用
.demoImg{ background-image: url("data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...."); }

Base64 在HTML中的使用
<img width="40" height="30" src="data:image/jpg;base64,/9j/4QMZRXhpZgAASUkqAAgAAAAL...." /">
  • 3、Base64的C++代码实现

base64.h:


#pragma once
#include <iostream>

#ifndef _MANAGED
typedef const unsigned char* BYTE_DATA_IN;
typedef unsigned char* BYTE_DATA_OUT;
#else
typedef array<Byte>^ BYTE_DATA_IN;
typedef array<Byte>^% BYTE_DATA_OUT;
#endif

// Encoding and decoding Base64 code
class Base64
{
public:

	// Encodes binary data to Base64 code
	// Returns size of encoded data.
	static int Encode(BYTE_DATA_IN inData,
		int dataLength,
		std::wstring& outCode,
		wchar_t CHAR_63 = '+', wchar_t CHAR_64 = '#', wchar_t CHAR_PAD = '=');

	// Decodes Base64 code to binary data
	// Returns size of decoded data.
	static int Decode(std::wstring& inCode,
		int codeLength,
		BYTE_DATA_OUT outData,
		wchar_t CHAR_63 = '+', wchar_t CHAR_64 = '#', wchar_t CHAR_PAD = '=');

	// Returns maximum size of decoded data based on size of Base64 code.
	static int GetDataLength(int codeLength);

	// Returns maximum length of Base64 code based on size of uncoded data.
	static int GetCodeLength(int dataLength);

};

std::string base64_encode(const char *bytes_to_encode, unsigned int in_len);
std::string base64_decode(const std::string& encoded_string);

base64.cpp:

#include "stdafx.h"
#include "base64.h"

// Encodes binary data to Base64 code
// Returns size of encoded data.
int Base64::Encode(BYTE_DATA_IN inData,
				   int dataLength,
				   std::wstring& outCode,
                   wchar_t CHAR_63, wchar_t CHAR_64, wchar_t CHAR_PAD)
{

#ifndef _MANAGED

//	STRING result;

	// output buffer which holds code during conversation
	int len = GetCodeLength( dataLength );
	wchar_t* out = new wchar_t[ len ];

	// charachers used by Base64
	static const wchar_t alph[] =
	{
		'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
		'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
		'0','1','2','3','4','5','6','7','8','9',CHAR_63,CHAR_64
	};

	// mask - first six bits
	const int mask = 0x3F;

	// used as temp 24-bits buffer
	union
	{
		unsigned char bytes[ 4 ];
		unsigned int block;
	} buffer;

	// coversation is done by taking three bytes at time of input data int temp
	// then four six-bits values are extracted, converted to base64 characters
	// and at the end they are written to output buffer
	for( int i = 0, j = 0, left = dataLength; i < dataLength; i += 3, j += 4, left -= 3 )
	{
		//------------------------
		// filling temp buffer

		// get first byte and puts it at MSB position in temp buffer
		buffer.bytes[ 2 ] = inData[ i ];

		// more data left?
		if( left > 1 )
		{
			// get second byte and puts it at middle position in temp buffer
			buffer.bytes[ 1 ] = inData[ i + 1 ];
			// more data left?
			if( left > 2 )
				// get third byte and puts it at LSB position in temp buffer
				buffer.bytes[ 0 ] = inData[ i + 2 ];
			else
				// zero-padding of input data (last bytes)
				buffer.bytes[ 0 ] = 0;
		}
		else
		{
			// zero-padding of input data (last two bytes)
			buffer.bytes[ 1 ] = 0;
			buffer.bytes[ 0 ] = 0;
		}

		//------------------------
		// constructing code from temp buffer
		// and putting it in output buffer

		// extract first and second six-bit value from temp buffer
		// and convert is to base64 character
		out[ j ] = alph[ ( buffer.block >> 18 ) & mask ];
		out[ j + 1 ] = alph[ ( buffer.block >> 12 ) & mask ];
		// more data left?
		if( left > 1 )
		{
			// extract third six-bit value from temp buffer
			// and convert it to base64 character
			out[ j + 2 ] = alph[ ( buffer.block >> 6 ) & mask ];
			// more data left?
			if( left > 2 )
				// extract forth six-bit value from temp buffer
				// and convert it to base64 character
				out[ j + 3 ] = alph[ buffer.block & mask ];
			else
				// pad output code
				out[ j + 3 ] = CHAR_PAD;
		}
		else
		{
			// pad output code
			out[ j + 2 ] = CHAR_PAD;
			out[ j + 3 ] = CHAR_PAD;
		}
	}

	outCode.resize(0);
	outCode.append( out, len );
	delete[] out;
	return len;

#else

	// encode
	outCode = System::Convert::ToBase64String( inData );

	// replace character if they are not standard
	if( CHAR_63 != '+' )
		outCode = outCode->Replace( '+', CHAR_63 );
	if( CHAR_64 != '/' )
		outCode = outCode->Replace( '/', CHAR_64 );
	if( CHAR_PAD != '=' )
		outCode = outCode->Replace( '=', CHAR_PAD );

	return outCode->Length;

#endif
}

// Decodes Base64 code to binary data
// Returns size of decoded data.
int Base64::Decode(std::wstring& inCode,
				   int codeLength,
				   BYTE_DATA_OUT outData,
                   wchar_t CHAR_63, wchar_t CHAR_64, wchar_t CHAR_PAD)
{

#ifndef _MANAGED

	// used as temp 24-bits buffer
	union
	{
		unsigned char bytes[ 4 ];
		unsigned int block;
	} buffer;
	buffer.block = 0;

	// number of decoded bytes
	int j = 0;

	for( int i = 0; i < codeLength; i++ )
	{
		// position in temp buffer
		int m = i % 4;

		wchar_t x = inCode[ i ];
		int val = 0;

		// converts base64 character to six-bit value
		if( x >= 'A' && x <= 'Z' )
			val = x - 'A';
		else if( x >= 'a' && x <= 'z' )
			val = x - 'a' + 'Z' - 'A' + 1;
		else if( x >= '0' && x <= '9' )
			val = x - '0' + ( 'Z' - 'A' + 1 ) * 2;
		else if( x == CHAR_63 )
			val = 62;
		else if( x == CHAR_64 )
			val = 63;

		// padding chars are not decoded and written to output buffer
		if( x != CHAR_PAD )
			buffer.block |= val << ( 3 - m ) * 6;
		else
			m--;

		// temp buffer is full or end of code is reached
		// flushing temp buffer
		if( m == 3 || x == CHAR_PAD )
		{
			// writes byte from temp buffer (combined from two six-bit values) to output buffer
			outData[ j++ ] = buffer.bytes[ 2 ];
			// more data left?
			if( x != CHAR_PAD || m > 1 )
			{
				// writes byte from temp buffer (combined from two six-bit values) to output buffer
				outData[ j++ ] = buffer.bytes[ 1 ];
				// more data left?
				if( x != CHAR_PAD || m > 2 )
					// writes byte from temp buffer (combined from two six-bit values) to output buffer
					outData[ j++ ] = buffer.bytes[ 0 ];
			}

			// restarts temp buffer
			buffer.block = 0;
		}

		// when padding char is reached it is the end of code
		if( x == CHAR_PAD )
			break;
	}

	return j;

#else

	// reverse changes of character before decoding data
	if( CHAR_63 != '+' )
		inCode = inCode->Replace( CHAR_63, '+' );
	if( CHAR_64 != '/' )
		inCode = inCode->Replace( CHAR_64, '/' );
	if( CHAR_PAD != '=' )
		inCode = inCode->Replace( CHAR_PAD, '=' );

	// decode
	outData = System::Convert::FromBase64String( inCode );
	return inCode->Length;

#endif
}

// Returns maximum size of decoded data based on size of Base64 code.
int Base64::GetDataLength(int codeLength)
{
	return codeLength - codeLength / 4;
}

// Returns maximum length of Base64 code based on size of uncoded data.
int Base64::GetCodeLength(int dataLength)
{
	int len = dataLength + dataLength / 3 + (int)( dataLength % 3 != 0 );

	// output code size must be multiple of 4 bytes
	if( len % 4 )
		len += 4 - len % 4;

	return len;
}

// there are 64 characters
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";


static inline bool is_base64(unsigned char c) {
	return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(const char *bytes_to_encode, unsigned int in_len) {
	std::string ret;
	int i = 0;
	int j = 0;
	unsigned char char_array_3[3];  // store 3 byte of bytes_to_encode
	unsigned char char_array_4[4];  // store encoded character to 4 bytes

	while (in_len--) {
		char_array_3[i++] = *(bytes_to_encode++);  // get three bytes (24 bits)
		if (i == 3) {
			// eg. we have 3 bytes as ( 0100 1101, 0110 0001, 0110 1110) --> (010011, 010110, 000101, 101110)
			char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; // get first 6 bits of first byte,
			char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); // get last 2 bits of first byte and first 4 bit of second byte
			char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); // get last 4 bits of second byte and first 2 bits of third byte
			char_array_4[3] = char_array_3[2] & 0x3f; // get last 6 bits of third byte

			for (i = 0; (i < 4); i++)
				ret += base64_chars[char_array_4[i]];
			i = 0;
		}
	}

	if (i)
	{
		for (j = i; j < 3; j++)
			char_array_3[j] = '\0';

		char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
		char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
		char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);

		for (j = 0; (j < i + 1); j++)
			ret += base64_chars[char_array_4[j]];

		while ((i++ < 3))
			ret += '=';

	}

	return ret;

}

std::string base64_decode(const std::string& encoded_string) {
	size_t in_len = encoded_string.size();
	int i = 0;
	int j = 0;
	int in_ = 0;
	unsigned char char_array_4[4], char_array_3[3];
	std::string ret;

	while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
		char_array_4[i++] = encoded_string[in_]; in_++;
		if (i == 4) {
			for (i = 0; i < 4; i++)
				char_array_4[i] = base64_chars.find(char_array_4[i]) & 0xff;

			char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
			char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
			char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

			for (i = 0; (i < 3); i++)
				ret += char_array_3[i];
			i = 0;
		}
	}

	if (i) {
		for (j = 0; j < i; j++)
			char_array_4[j] = base64_chars.find(char_array_4[j]) & 0xff;

		char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
		char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);

		for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
	}

	return ret;
}

后续

如果你觉得该方法或代码有一点点用处,可以给作者点个赞;╮( ̄▽ ̄)╭
如果你感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进。o_O???
谢谢各位童鞋们啦( ´ ▽ ` )ノ ( ´ ▽ ` )っ!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值