社区,我对C的经验很少,并且现在处于学习曲线上。
我正在做一个小项目,涉及在C中将一个32个字符的字符串分成4个字符串,每个字符串8个字符。
32个字符的字符串应类似于32位指令。那些“32位”被分为4个“8位”字符串,我想将其打印为十六进制。下面的代码是我到目前为止所获得的。我正在使用的数据类型是我在其余代码中使用的数据类型。我打算将unsigned char t
变量输入到Substitution Box程序中,该程序将给我等效于S-Box查找表中的t
char。
下面的代码在我看来应该可以工作
unsigned char inst[] = "10101010101010101111111100111101";
unsigned char in[8];
for (int i = 0; i < 33; i++){
if (i%8 == 0 && i != 0) {
unsigned char t = (unsigned char) strtol(in, NULL, 2);
printf("%x \n", t);
}
in[i%8] = inst[i];
printf("%c ", in[i%8]);
}
但是输出看起来像这样:
1 0 1 0 1 0 1 0 3d
1 0 1 0 1 0 1 0 3d
1 1 1 1 1 1 1 1 3d
0 0 1 1 1 1 0 1 3d
我可以看到
in[i%8] = inst[i];
行从chars
正确读取了inst[]
,但是if (i%8 == 0 && i != 0) {
unsigned char t = (unsigned char) strtol(in, NULL, 2);
printf("%x \n", t);
}
条件语句打印错误的十六进制。
输出看起来应该像这样
1 0 1 0 1 0 1 0 aa
1 0 1 0 1 0 1 0 aa
1 1 1 1 1 1 1 1 ff
0 0 1 1 1 1 0 1 3d
任何帮助,将不胜感激。
最佳答案
当前代码存在问题:
char in[4][8+1];
而不是char in[8]
。您需要为零终止留出空间。 这似乎是要求:
在这种情况下,您可以简单地对输入字符串进行4次迭代:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
const char* inst = "10101010101010101111111100111101";
char in [4][8+1];
puts("Bin Hex");
for(size_t i=0; i<4; i++)
{
memcpy(in[i], &inst[i*8], 8);
in[i][8] = '\0';
unsigned long val = strtoul(in[i], NULL, 2);
printf("%.8s %.2lX\n", in[i], val);
}
}
输出:
Bin Hex
10101010 AA
10101010 AA
11111111 FF
00111101 3D
关于c - 在c中将32的字符串分成4 8十六进制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54824948/