传递参数时出错,并将其转换为十六进制
Error when passing arguments and convert it to hexadecimal
如何通过参数插入文本并自动将其转换为十六进制?
I tried with:
unsigned char aesKey[32] = argv[1];
but get errors
输出如下所示:
unsigned char aesKey[32] = {
0x53, 0x28, 0x40, 0x6e, 0x2f, 0x64, 0x63, 0x5d, 0x2d, 0x61, 0x77, 0x40, 0x76, 0x71, 0x77, 0x28,
0x74, 0x61, 0x7d, 0x66, 0x61, 0x73, 0x3b, 0x5d, 0x66, 0x6d, 0x3c, 0x3f, 0x7b, 0x66, 0x72, 0x36
};
unsigned char *buf;
aes256_context ctx;
aes256_init(&ctx, aesKey);
for (unsigned long i = 0; i < lSize/16; i++) {
buf = text + (i * 16);
aes256_encrypt_ecb(&ctx, buf);
}
aes256_done(&ctx);
Thanks in advance
在C和c++中,当你有像
这样的代码时char name[]="John Smith";
编译器在编译时知道该char数组的大小,以及所有值的大小。因此,它可以在堆栈帧上分配它并为其赋值。
当你有类似的代码时Char * STRPTR = foo();Char str[] = str;
编译器不知道strptr所指向的字符串的大小和值是多少。这就是为什么这在C/c++中是不允许的。
换句话说,只能将字符串字面值赋值给字符数组,而且也只能在声明时赋值。
char name[] = "John Smith";
是被允许的。
char name[32];
name = "John Smith";
使用memcpy
所以你可以使用内存。(或者使用其他人提到的c++替代品)
unsigned char *aesKey;
size_t len = (strlen(argv[1])+1)*sizeof(unsigned char);
aesKey = malloc(len);
memcpy(aesKey, argv[1], len);
旧方案
(这是我之前的答案,上面的答案更好)所以你需要使用strong。
unsigned char aesKey[32];
strncpy((char *) aesKey, argv[1], 32);
注意这个例程是强的而不是强的。策略是不安全的。(感谢PRouleau的arg修复)
如果strncpy在Visual Studio中不可用,那么你可能不得不尝试strcpy_s(感谢Google: user:427390)
在C/c++中,编译器不会自动操作数组。你必须指定如何复制它们。
旧的好方法是使用memcpy()。更现代的方法是使用std::copy()。在任何情况下,你必须在复制到aesKey之前验证argv[1]的长度。
要转换为十六进制,您可能必须将像"AAEE3311"这样的字符串(最多2*32个字符)转换为字节。您应该使用std::istringstream并逐个填充aesKey位置。
,
std::istringstream Input(argv[1]);
Input >> std::hex >> aesKey[0];
我想象一个程序是这样被调用的——
myprog 0x53 0x28 0x40 0x6e 0x2f 0x64 0x63
在程序内部,我将有一个循环将参数赋值给数组-
const int size = 32;
unsigned char aesKey[size];
char* p;
for (int i = 1; i < argc || i < size; ++i)
{
aesKey[i] = (unsigned char)strtol(argv[i], &p, 16);
}
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为什么mpfr_printf与十六进制浮点(%a转换说明符)的printf不同
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- 如何将带有十六进制值的 std::string 转换为 std::vector<无符号字符>
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 在Arduino中将字符串转换为(逗号分隔的十六进制)字符串到无符号字符数组
- 将 std::string( "x3BxDEx7C" ) 转换为可读的十六进制字符串?
- 将十六进制转换为 DEC
- C++ 将十六进制字符串表示形式转换为十六进制字符串表示形式
- 字符数组到十六进制字符串的转换 - 意外输出
- C++将 wwn 字符串转换为识别为十六进制的数据类型
- 将字符串存储为十六进制而不进行转换
- 将字符串转换为十六进制数组c++
- 十六进制到十进制转换的未清理答案
- 是否有函数或公式可以在 c++ 中将字符串"of letters"转换为十六进制
- C++十六进制字符串转换为十六进制的字符 *
- 转换十六进制并存储为字节