2017-01-16 93 views
0

如何通过UNIX套接字发送编码为base64的example.wav文件字节?二进制数组到base64

char* readFileBytes(const char *name){ 
FILE *fl = fopen(name, "rb"); 
fseek(fl, 0, SEEK_END); 
long len = ftell(fl); 
char *ret = malloc(len); 
fseek(fl, 0, SEEK_SET); 
fread(ret, 1, len, fl); 
fclose(fl); 
return ret; 
} 

这是我从文件中读取的。 现在我需要从这个数组获取字符串或东西,因为我需要编码,当我尝试:

printf("%s\n", ret); 
Output: RIFF�3 

程序只编码RIFF3。

我能做到循环

for(int i=0; i<len;i++){printf("%u ",ren[0])} 

然后我得到更多的东西intresting,但是,我怎么能编码整个二进制数组。 后来我会通过UNIX套接字发送编码的字符串,但这不是ATM的情况。

编辑:> 我使用http://fm4dd.com/programming/base64/base64_stringencode_c.htm算法进行编码。二进制文件错误吗?

+0

不能使用字符串函数与二进制数据。二进制数据可能包含数据内任意位置的字节,这与字符串终止符使用的值相同。它当然也可以包含您在输出中看到的不可打印的“字符”。 –

+0

那么我应该如何通过套接字发送二进制数据,或者转换为base64? –

+1

可能的重复[我如何base64编码(解码)在C?](http://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c) –

回答

0

您正在使用的函数(b64_encode)只能对字符串进行编码。 确保您修改该函数,以便遍历缓冲区中的所有字符。

也许这样的事情就可以了(我没有测试的代码):

/* encode - base64 encode a stream, adding padding if needed */ 
void b64_encode(char *clrstr, int length, char *b64dst) { 
    unsigned char in[3]; 
    int i, len = 0; 
    int j = 0; 

    b64dst[0] = '\0'; 
    while(j<length) { 
    len = 0; 
    for(i=0; i<3; i++) { 
    in[i] = (unsigned char) clrstr[j]; 
    if(j<length) { 
     len++; j++; 
     } 
     else in[i] = 0; 
    } 
    if(len) { 
     encodeblock(in, b64dst, len); 
    } 
    } 
}