[英]Convert hexidecimal char array to u8 array in C
Right now I have a u8 array that I successfully converted to a hexidecimal char array. 现在我有一个u8数组,我已成功将其转换为十六进制char数组。 Now, trying to change it back into a u8 array has been a doozy.
现在,尝试将其改回u8阵列已经很麻烦了。 I tried this code:
我尝试了这段代码:
// DEMO:
char *message = "0f236a1f";
int i;
u8 final[4];
memset(final, 0, 4);
char* part = "00";
for (i = 0; i < 4; i++)
{
memcpy(part, &message[i*2], 2);
u8 num = 0;
sscanf(part, "%x", &num);
printf("%i", num);
final[i] = num;
}
I prepopulate everything with values to prevent stay memory values from messing up large portions of zeros I have in my actual data. 我用值预填充了所有内容,以防止剩余内存值弄乱我实际数据中的大部分零。 Despite everything I have tried, occasionally the wrong values are assigned, and I can't find any other method online which does the same thing.
尽管我已经尝试了所有方法,但有时还是会分配错误的值,而且我找不到在线上执行相同操作的任何其他方法。 Help me if you can, I hate C.
如果可以的话,请帮助我,我讨厌C。
EDIT: 编辑:
I revised my code, and am showing the real thing now, to see if it helps. 我修改了代码,现在显示真实的东西,看是否有帮助。 The variable message is 464 zeros in a giant
char *
array. 巨型
char *
数组中的可变消息为464个零。 The console is still occasionally printing numbers besides zero, not sure why: 控制台偶尔仍会打印除零以外的数字,不确定为什么:
int i;
u8 final[232];
memset(final, 0, 232);
char part[3] = "00";
part[2] = 0;
for (i = 0; i < 232; i++)
{
memcpy(part, &message[i*2], 2);
unsigned int num = 0;
sscanf(part, "%x", &num);
printf("%i", num);
final[i] = (u8)num;
}
You are creating undefined behavior with these lines: 您正在使用以下行创建未定义的行为:
char* part = "00";
for (i = 0; i < 4; i++)
{
memcpy(part, &message[i*2], 2);
...
sscanf(part, "%x", &num);
part
points to read only memory (this is why with strings like this we usually declare them as const char*
to cause a compiler error when modification attempts occur) More info here. part
指向只读内存(这就是为什么在这样的字符串中,我们通常将它们声明为const char*
从而在进行修改尝试时导致编译器错误) 。
You should allocate enough space for your string and null terminator with: 您应该使用以下命令为字符串和空终止符分配足够的空间:
char part[3] = "00";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.