将ASCII字符串编码为Base-64格式

Base 64是一种编码方案,它将二进制数据转换为文本格式,这样编码的文本数据就可以轻松地通过网络传输,而不会损坏,也不会丢失任何数据。Base64通常用于许多应用程序,包括通过MIME发送电子邮件,以及以XML格式存储复杂数据。 向网络发送普通二进制数据的问题在于,位可能会被底层协议误解,在接收节点产生不正确的数据,这就是我们使用此代码的原因。

null

为什么以64为基数?

对数据进行编码后生成的文本中包含的字符广泛存在于许多字符集中,因此数据被破坏或修改的可能性非常小。

如何转换成base 64格式?

base64中的字符集为

char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" // 64 characters

基本思想

让我们举个例子。我们必须将字符串“MENON”编码为base64格式。让我们把“美农”称为 输入_str ,位于base64字符集(“ABC..+/”)之上 字符集 结果编码字符串为 瑞苏街 .

  1. 从中选取3个字符 输入_str i、 e“MEN”由于每个字符大小为8位,我们将有(8*3)24位。
  2. 将它们分组在一个6位的块中(24/6=4个块)。(为什么是6?)因为2^6=64个字符,我们可以用6位来表示每个字符 字符集 .
  3. 将每个6位的数据块转换为相应的十进制值。Decimal value Acquired是生成的编码字符的索引 字符集 .
  4. 所以每3个字符 输入_str 我们将收到4个字符 瑞苏街 .
  5. 如果我们的文本少于3个字符呢 输入_str 左,即“开”。我们有16位,块将是16/6=2块。最右边的4位不能构成一个正确的块(1块=6位),所以我们在块的右边附加0,使其成为一个正确的块,即在右边附加2个0。现在我们有3个适当的块,找到每个块对应的十进制值来得到索引。
  6. 因为里面只有不到3个字符(“ON”) 输入_str 我们将在res_str中添加“=”,例如“ON”,这里3-2=1填充“=”在 瑞苏街 .

实例

1.将“MENON”转换为其(8位)二进制格式。获取字符串的每个字符,并写出其8位二进制表示形式。 待编码字符串中字符的ASCII值

M : 77 (01001101), E : 69 (01000101), N : 78 (01001110), O : 79 (01001111), N : 78 (01001110)

上述字符串的结果二进制数据为:

01001101 01000101 01001110 01001111 01001110

2.从左边开始做块 6. 直到所有位都被覆盖 比特流:

(010011) (010100) (010101) (001110) (010011) (110100) (1110)

3.如果最右边的块小于6位,只需在该块的右边附加0,使其成为6位。在上面的例子中,我们必须附加2个零,使其为6。 比特流:

(010011) (010100) (010101) (001110) (010011) (110100) (111000)

请注意粗体的零。 4.从输入字符串(“MEN”)中提取3个字符,即24位,并找到相应的十进制值(索引到字符集)。 阻碍:

INDEX --> (010011) : 19, (010100) : 20, (010101) : 21, (001110) : 14char_set[19] = T, char_set[20] = U, char_set[21] = V, char_set[14] = O

因此,我们的输入_str=“MEN”将转换为编码字符串“TUVO”。 5.取剩余字符(“ON”)。我们必须用1“=”填充结果编码字符串,因为输入字符串中的字符数少于3。(3–2=1填充) 阻碍:

INDEX --> (010011) : 19 (110100) : 52 (111000) : 56char_set[19] = T char_set[52] = 0 char_set[56] = 4So our input_str = "ON" will be converted to encoded string "T04=".

例如:

Input : MENON // string in ASCIIOutput :TUVOT04= // encoded string in Base 64.Input : geeksforgeeksOutput : Z2Vla3Nmb3JnZWVrcw==

方法 :

我们可以使用位运算符对字符串进行编码。我们可以取一个整数“val”(在大多数编译器上通常为4字节),并将输入字符的所有字符(一次3个)存储在val中。输入字符的字符将存储在val中 以比特的形式。我们将使用(或运算符)存储字符和(左移位)8,以便 给另外8位腾出空间。以类似的方式,我们将使用(右移)一次从val 6中检索位 用63(111111)求位的值,这将给我们提供索引。然后我们可以通过查字符集的索引得到我们的结果字符。

C++

// C++ program to encode an ASCII
// string in Base64 format
#include <iostream>
using namespace std;
#define SIZE 1000
// Takes string to be encoded as input
// and its length and returns encoded string
char * base64Encoder( char input_str[], int len_str)
{
// Character set of base64 encoding scheme
char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ;
// Resultant string
char *res_str = ( char *) malloc (SIZE * sizeof ( char ));
int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
int i, j, k = 0;
// Loop takes 3 characters at a time from
// input_str and stores it in val
for (i = 0; i < len_str; i += 3)
{
val = 0, count = 0, no_of_bits = 0;
for (j = i; j < len_str && j <= i + 2; j++)
{
// binary data of input_str is stored in val
val = val << 8;
// (A + 0 = A) stores character in val
val = val | input_str[j];
// calculates how many time loop
// ran if "MEN" -> 3 otherwise "ON" -> 2
count++;
}
no_of_bits = count * 8;
// calculates how many "=" to append after res_str.
padding = no_of_bits % 3;
// extracts all bits from val (6 at a time)
// and find the value of each block
while (no_of_bits != 0)
{
// retrieve the value of each block
if (no_of_bits >= 6)
{
temp = no_of_bits - 6;
// binary of 63 is (111111) f
index = (val >> temp) & 63;
no_of_bits -= 6;
}
else
{
temp = 6 - no_of_bits;
// append zeros to right if bits are less than 6
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str[k++] = char_set[index];
}
}
// padding is done here
for (i = 1; i <= padding; i++)
{
res_str[k++] = '=' ;
}
res_str[k] = ' ' ;
return res_str;
}
// Driver code
int main()
{
char input_str[] = "MENON" ;
int len_str;
// calculates length of string
len_str = sizeof (input_str) / sizeof (input_str[0]);
// to exclude ' ' character
len_str -= 1;
cout << "Input string is : " << input_str << endl;
cout << "Encoded string is : " << base64Encoder(input_str, len_str)<< endl;
return 0;
}
// This code is contributed by shivanisinghss2110


C

// C program to encode an ASCII
// string in Base64 format
#include <stdio.h>
#include <stdlib.h>
#define SIZE 1000
// Takes string to be encoded as input
// and its length and returns encoded string
char * base64Encoder( char input_str[], int len_str)
{
// Character set of base64 encoding scheme
char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ;
// Resultant string
char *res_str = ( char *) malloc (SIZE * sizeof ( char ));
int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
int i, j, k = 0;
// Loop takes 3 characters at a time from
// input_str and stores it in val
for (i = 0; i < len_str; i += 3)
{
val = 0, count = 0, no_of_bits = 0;
for (j = i; j < len_str && j <= i + 2; j++)
{
// binary data of input_str is stored in val
val = val << 8;
// (A + 0 = A) stores character in val
val = val | input_str[j];
// calculates how many time loop
// ran if "MEN" -> 3 otherwise "ON" -> 2
count++;
}
no_of_bits = count * 8;
// calculates how many "=" to append after res_str.
padding = no_of_bits % 3;
// extracts all bits from val (6 at a time)
// and find the value of each block
while (no_of_bits != 0)
{
// retrieve the value of each block
if (no_of_bits >= 6)
{
temp = no_of_bits - 6;
// binary of 63 is (111111) f
index = (val >> temp) & 63;
no_of_bits -= 6;
}
else
{
temp = 6 - no_of_bits;
// append zeros to right if bits are less than 6
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str[k++] = char_set[index];
}
}
// padding is done here
for (i = 1; i <= padding; i++)
{
res_str[k++] = '=' ;
}
res_str[k] = ' ;' ;
return res_str;
}
// Driver code
int main()
{
char input_str[] = "MENON" ;
int len_str;
// calculates length of string
len_str = sizeof (input_str) / sizeof (input_str[0]);
// to exclude ' ' character
len_str -= 1;
printf ( "Input string is : %s" , input_str);
printf ( "Encoded string is : %s" , base64Encoder(input_str, len_str));
return 0;
}


输出

Input string is : MENONEncoded string is : TUVOT04=

时间复杂性: O(2*N)向val中插入位+从val中检索位 练习: 实现一个base64解码器 本文由 阿什普里特·苏丹 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享