2017-01-16 73 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); 
    } 
    } 
}