char数组转换为unsigned char *

时间:2020-06-15 14:26:37

标签: c++ pointers

所以我有一个接收指针的函数:

int myfunc( const char *token, unsigned char *plaintext )

我做我的事情,最后得到一个char数组:

unsigned char my_plaintext[1024];

现在,我需要将该指针(纯文本)设置为my_plaintext中的内容。 我尝试了许多不同的方法,但我还没有弄清楚这一点...

这部分位于cpp文件中,我什至尝试过:

std::string tmpstr( my_plaintext );

但这又回来了:

token_crypto.cpp:131:13: error: invalid conversion from 'char*' to 'unsigned char*' [-fpermissive]
         my_plaintext
         ^~~~~~~~~~~~

还有

std::string tmpstr( (char *)my_plaintext );

'�5�B'

这确实可以编译,但是内容都是错误的:

编辑:

my_plaintext的内容很好:

int myfunc( const char *token, unsigned char *plaintext ) {
    unsigned char my_plaintext[1024];
    ... some processing stuff (specifically gcm_decrypt) to which is pass my_plaintext ...

    cout << my_plaintext

    // prints: hello:world

但是随后我尝试将纯文本的内容设置为my_plaintext中的内容,要么编译失败,要么打印一些奇怪的字符。

2 个答案:

答案 0 :(得分:0)

如果您知道plaintext已经指向1024长(或更长)的数组,则可以使用memmove()

int myfunc( const char *token, unsigned char *plaintext )
{
    unsigned char my_plaintext[1024];
    /* ... fill in my_plaintext here ... */
    memmove(plaintext, my_plaintext, 1024);
    /* ... rest of function ... */
}

请注意,memmove的参数是目的地,然后是源,而不是相反。

取决于函数的调用者,以确保它们传递的指针至少指向1024个字节。

在这种情况下,您可以改用memcpy(),但是通常使用memmove()是一种好习惯。

答案 1 :(得分:-1)

C ++字符串构造函数不采用无符号字符*。请参阅此处的C ++参考:

http://www.cplusplus.com/reference/string/string/string/

您需要将无符号char数组转换为char数组。在此处查看操作方法:

How to Convert unsigned char* to std::string in C++?

相关问题