在控制台中打印一个十六进制数组
Printing a hex array in console
我有一个 uint8_t
类型的数组,4x4 维度,我使用嵌套的 for 循环来显示数组,十六进制值通过 sprintf()
.
转换为十六进制字符串
void hexD(uint8_t state[4][4])
{
char x[2];
for(int i = 0; i < 4; i++)
{
cout << "\n";
for(int j = 0; j < 4; j++)
{
cout << j <<"\n"; //displays the value of j
sprintf(x, "%x", state[i][j]);
cout << x << "\t";
}
}
}
问题出在内部 for 循环,它无限运行,因为 j 的值从 0 开始,然后是 1,然后是 2,但不是去 3,而是回到 1,j 在 1 和 2 之间交换,因此 [=21 中的循环=]无限。
任何解决方案。
谢谢。
您的x
只有两个空格,但您正在向其中写入更多字符。比如一个0
十六进制就是"00"
,两个字符加上一个结束'[=13=]'
.
这会覆盖相邻的内存,而您的 j
恰好在那里并被覆盖。
增加 x[]
的大小,应该可以。
根据您在 state[4][4]
中的价值观,您很可能最终
溢出 x
数组(请记住,您最多需要一个地方 FF
(2 个字符)+ 1 个用于终止 '[=14=]'
)。
那是未定义的行为。
修复它 (char x[3];
),你应该没问题。这是一个 mcve:
#include <iostream>
#include <cstdint>
#include <cstdio>
using namespace std;
void hexD(uint8_t state[4][4])
{
char x[3];
for(int i = 0; i < 4; i++)
{
cout << "\n";
for(int j = 0; j < 4; j++)
{
cout << j <<"\n"; //displays the value of j
sprintf(x, "%x", state[i][j]);
cout << x << "\t";
}
}
}
uint8_t state[4][4]={
255,255,255,255,
0, 1, 2, 3,
0, 1, 2, 3,
0, 1, 2, 3,
};
int main()
{
hexD(state);
}
char x[2];
您的 "hex output" 只有两个字节,但 null
字符没有可用的 space。
向容量较小的数组写入更多内容是未定义的行为。
将 x
数组大小增加到 3:
char x[3];
因为根据 sprintf
:
A terminating null character is automatically appended after the
content.
因此,您总共有三个字符 包括 null
个字符。
我有一个 uint8_t
类型的数组,4x4 维度,我使用嵌套的 for 循环来显示数组,十六进制值通过 sprintf()
.
void hexD(uint8_t state[4][4])
{
char x[2];
for(int i = 0; i < 4; i++)
{
cout << "\n";
for(int j = 0; j < 4; j++)
{
cout << j <<"\n"; //displays the value of j
sprintf(x, "%x", state[i][j]);
cout << x << "\t";
}
}
}
问题出在内部 for 循环,它无限运行,因为 j 的值从 0 开始,然后是 1,然后是 2,但不是去 3,而是回到 1,j 在 1 和 2 之间交换,因此 [=21 中的循环=]无限。
任何解决方案。
谢谢。
您的x
只有两个空格,但您正在向其中写入更多字符。比如一个0
十六进制就是"00"
,两个字符加上一个结束'[=13=]'
.
这会覆盖相邻的内存,而您的 j
恰好在那里并被覆盖。
增加 x[]
的大小,应该可以。
根据您在 state[4][4]
中的价值观,您很可能最终
溢出 x
数组(请记住,您最多需要一个地方 FF
(2 个字符)+ 1 个用于终止 '[=14=]'
)。
那是未定义的行为。
修复它 (char x[3];
),你应该没问题。这是一个 mcve:
#include <iostream>
#include <cstdint>
#include <cstdio>
using namespace std;
void hexD(uint8_t state[4][4])
{
char x[3];
for(int i = 0; i < 4; i++)
{
cout << "\n";
for(int j = 0; j < 4; j++)
{
cout << j <<"\n"; //displays the value of j
sprintf(x, "%x", state[i][j]);
cout << x << "\t";
}
}
}
uint8_t state[4][4]={
255,255,255,255,
0, 1, 2, 3,
0, 1, 2, 3,
0, 1, 2, 3,
};
int main()
{
hexD(state);
}
char x[2];
您的 "hex output" 只有两个字节,但 null
字符没有可用的 space。
向容量较小的数组写入更多内容是未定义的行为。
将 x
数组大小增加到 3:
char x[3];
因为根据 sprintf
:
A terminating null character is automatically appended after the content.
因此,您总共有三个字符 包括 null
个字符。