如何将unsigned char数组转换为base64字符串?

时间:2014-03-07 17:34:20

标签: c arrays string base64

我有一个类型为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.

有没有更好的方法来转换它或者是否有一些我需要改变,因为我试图传入一个unsigned char数组。谢谢!

2 个答案:

答案 0 :(得分:1)

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

您可以使用

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

答案 1 :(得分:1)

  

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

char * buffer[2850];

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

我怀疑这是你想要的。

使用

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

定义2850个元素的字符数组,即用于保存2849 char s加0 - 终结符的C-“字符串。


参考问题的标题“ ...转换一个unsigned char数组... ”请注意,它取决于使用的编译器是否将声明为char的变量处理signedunsigned。所以最好明确一点:

unsigned char buffer[2850] = "";