【问题标题】:Unsigned char to char* and int in C?C中的无符号字符到char *和int?
【发布时间】:2012-09-15 11:59:46
【问题描述】:

处理一些需要在函数中使用无符号字符的加密,但希望在解密后转换为字符以供使用。所以,我有:

unsigned char plaintext[16];
char *plainchar;
int plainint;

... Code now populates plaintext with data that happens to all be plain text

现在,假设明文实际上是“0123456789”的数据字符串。如何将纯文本的值转换为“012456789”的plainchar,同时将plainint 转换为123456789?

-- 编辑--

当明文等于“AAAAAAAAAA105450”时这样做:

unsigned char plaintext[16];
char *plainchar;
int plainint;

... Code now populates plaintext with data that happens to all be plain text

plainchar = (char*)plaintext;

使 plainchar 等于“AAAAAAA105450╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠5┤∙7”,大小为. 加密代码是 rijndael 示例代码,所以应该可以正常工作。

谢谢, 本

【问题讨论】:

标签: c visual-studio-2010 char int unsigned-char


【解决方案1】:

您的纯文本字符串未终止。所有字符串都必须有一个额外的字符来表示字符串的结尾。这个角色是'\0'

plaintext 变量声明为

unsigned char plaintext[17];

在你完成解密后添加这个

plaintext[last_pos] = '\0';

last_pos更改为解密文本的最后一个位置,默认为16(数组的最后一个索引)。

【讨论】:

  • 哇。我已经离开C太久了。像魅力一样工作。谢谢!
【解决方案2】:

对于 unsigned char 到 char*

plainchar = (char*)plaintext;

for unsigned to int

sscanf( plainchar, "%d", &plainint );

【讨论】:

  • 检查你的加密算法
  • @BenCurtis:更新您的问题,而不是使用 cmets。
  • 感谢(也感谢@Sodved),除了这不会为我创造预期的结果。出于某种原因,如果明文是“AAAAAA123456”并且我执行上述操作,则 plainchar 现在等于“AAAA123456”并且 sizeof 报告 51。想法?
  • @BenCurtis 你的意思是 strlen 报告 51? sizeof 只关心其参数的类型sizeof plaincharchar* 的大小,而不管plaintext 的内容是什么。
【解决方案3】:

我觉得很简单

plainchar = (char*)plaintext;
sscanf( plainchar, "%d", &plainint );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-23
    • 2011-11-02
    • 2011-11-25
    • 1970-01-01
    • 2011-01-27
    • 2012-04-22
    • 2013-05-12
    • 2012-05-20
    相关资源
    最近更新 更多