我的问题是试图解码一个base64 / UTF-16LE字符串。此解码的结果始终是第一个字符。如果将字符串解码为utf-8 / ascii / windows1252,则结果是正确的。
有人能有现成的解决方案吗?
我使用的是来自互联网的标准代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
b64_decode_string("SABlAGwAbABvAA==");
return 0;
}
char base64decode_lut[] = {
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
64, 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, 64, 64, 64, 64, 64,
64, 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, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
};
void base64decode(char *src, char *dest, int len)
{
int i=0, slen=strlen(src);
for(i=0;i<slen&&i<len;i+=4,src+=4)
{
char c1=base64decode_lut[*src], c2=base64decode_lut[*(src+1)], c3=base64decode_lut[*(src+2)], c4=base64decode_lut[*(src+3)];
*(dest++)=(c1&0x3F)<<0x2|(c2&0x30)>>0x4;
*(dest++)=(c3!=64)?((c2&0xF)<<0x4|(c3&0x3C)>>0x2):'\0';
*(dest++)=(c4!=64)?((c3&0x3)<<0x6|c4&0x3F):'\0';
}
*dest='\0'; // Append terminator
}
int b64_decode_string(char *source)
{
int dest_size;
int res;
char *dest;
dest_size = strlen(source);
dest = (char *)malloc(dest_size);
memset(dest,0,dest_size);
base64decode(source, dest, dest_size);
printf("Decode: %s", dest);
}发布于 2020-08-12 03:45:12
只对第一个字符进行解码的原因是因为第二个字符以0x00字节开始,所以调用strlen() (仅适用于ascii字符串)返回一个非常小的数字(如1或2),而不是字符串的实际长度。
建议熟悉宽类型和处理宽字符的函数,比如:wprintf()和字符串的‘wchar_t’修饰符:-L和头文件:wchar.h
发布于 2020-08-12 03:54:44
这里没有使用C字符串,因此不要使用诸如strlen();之类的字符串函数
并考虑使用unsigned char作为数组的类型
unsigned char base64decode{} = {...在这种情况下,数组元素的数量可以由以下语句确定:
size_t len = sizeof(base64decode_lut)/sizeof(base64decode_lut[0]);https://stackoverflow.com/questions/63364821
复制相似问题