【问题标题】:How can I convert an unsigned char array into a base64 string?如何将 unsigned char 数组转换为 base64 字符串?
【发布时间】:2014-03-07 17:34:20
【问题描述】:

我有一个 unsigned char buffer[2850] 类型的大型缓冲区数组,我想将其转换为 Base64 字符串。我正在尝试使用可以在 on github 找到的 libb64 库

这是我尝试转换的方式:

char* encode(const char* input)
{
    /* set up a destination buffer large enough to hold the encoded data */
    char* output = (char*)malloc(SIZE);
    /* keep track of our encoded position */
    char* c = output;
    /* store the number of bytes encoded by a single call */
    int cnt = 0;
    /* we need an encoder state */
    base64_encodestate s;

    /*---------- START ENCODING ----------*/
    /* initialise the encoder state */
    base64_init_encodestate(&s);
    /* gather data from the input and send it to the output */
    cnt = base64_encode_block(input, strlen(input), c, &s);
    c += cnt;
    /* since we have encoded the entire input string, we know that
     there is no more input data; finalise the encoding */
    cnt = base64_encode_blockend(c, &s);
    c += cnt;
    /*---------- STOP ENCODING  ----------*/

    /* we want to print the encoded data, so null-terminate it: */
    *c = 0;

    return output;
}

char *encodedBuffer;
encodedBuffer = encode(buffer);

但我收到了警告

Passing 'unsigned char [2850]' to parameter of type 'const char *' converts between pointers to integer types with different sign.

有没有更好的方法来转换它,或者有什么我需要改变的,因为我试图传入一个无符号字符数组。谢谢!

【问题讨论】:

  • encodedBuffer = encode((const char*)buffer);?
  • @JoachimIsaksson 我真的是 C 新手,在缓冲区前面添加 (const char*) 会动态改变类型吗?
  • unsigned char *buffer[2850] 不是无符号字符数组;它是一个包含 2850 个指针的数组。如果那不是您的真实代码,请发布它。
  • 它只是告诉编译器在这种情况下可以将unsigned char[2850] 处理为const char*。基本上它告诉编译器“我知道我在做什么,所以不要打扰我”,所以如果你是一个初学者,你应该知道像这样将任何类型转换为任何其他类型并不总是安全的。
  • 感谢您的解释。

标签: c arrays string base64


【解决方案1】:

您的缓冲区是char** 类型。您需要传递char* 类型之一。

你可以使用

const char *buffer = "whatever";
encode(buffer);

【讨论】:

  • 如果我的缓冲区是一个十六进制值数组(它是一个字节数组),这会起作用吗
  • @Stavros_S 您可以使用strncpy 将您的十六进制复制到char*
  • 十六进制值存储在数组缓冲区中,该数组缓冲区被声明为'unsigned char buffer[2850]' 我认为 strncpy 不允许我这样做,因为缓冲区不是 const char .
【解决方案2】:

我有一个 unsigned char *buffer[2850] 类型的大型缓冲区数组,我想转换它

char * buffer[2850];

是一个包含 2850 个指向 char 的指针的数组。

我怀疑这是你想要的。

使用

char buffer[2850] = ""; /* The = "" inits the array to all 0s, that is to the empty string "". */

定义一个包含 2850 个元素的字符数组,即包含 2849 个 chars 加上 0-终止符的 C-“字符串”。


参考问题标题“...convert an unsigned char array ...”请注意,声明为char的变量是否会被@处理取决于使用的编译器987654327@ 或unsigned。所以为了确保最好是明确的:

unsigned char buffer[2850] = "";

【讨论】:

  • 欣赏建议。当我尝试使用 %s nothing display 注销新编码的缓冲区时,我已经实现了您在此处提到的内容。我在 xcode 中为 OSX 构建这个。
  • @Stavros_S:不客气。由于您现在面临的问题与此问题不同,您可能想针对您当前的问题提出另一个新问题。
猜你喜欢
  • 2018-09-18
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
相关资源
最近更新 更多