字符数组到无符号字符 *

char array to unsigned char *

本文关键字:字符 无符号 数组      更新时间:2023-10-16

所以我有这个函数,它接收一个指针:

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

我做我的事情,最终得到一个字符数组:

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编译失败或打印一些奇怪的字符的任何内容。

如果您知道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()是一种很好的做法。

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

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

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

如何在C++中将无符号字符*转换为标准::字符串?