【问题标题】:Binary array to base64二进制数组到base64
【发布时间】:2017-01-16 15:08:34
【问题描述】:

如何通过 UNIX 套接字发送 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

程序仅对 RIFF 3 进行编码。

我可以循环

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

然后我得到一些更有趣的东西,但是,我如何编码整个二进制数组。 稍后我将通过 UNIX 套接字发送编码字符串,但 ATM 并非如此。

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

【问题讨论】:

  • 您不能对二进制数据使用字符串函数。二进制数据可能包含数据内部任何位置为零的字节,这与用于字符串终止符的值相同。它当然也可以包含您在输出中看到的不可打印的“字符”。
  • 那我应该如何通过socket发送二进制数据,或者转换成base64?
  • base64 的全部想法不就是将二进制数据转换为可打印的字符串吗?
  • 以二进制形式打开文件 fopen(name, "rb")

标签: c arrays sockets base64 binaryfiles


【解决方案1】:

您使用的函数 (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 );
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2011-12-30
    • 2014-11-06
    相关资源
    最近更新 更多