简体   繁体   English

在控制台中打印十六进制数组

[英]Printing a hex array in console

I have a uint8_t type array, 4x4 dimensions, I have use nested for loops to display the array, hex values are converted to hex string through sprintf() . 我有一个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";
    }
}
}

The problem is inner for loop which runs endlessly as value of j starts from 0 then 1 then 2 but instead of going to 3 it gets back to 1, j swaps between 1 and 2 thus the loop in running infinitely. 问题是for循环内部不断循环运行,因为j的值从0开始,然后从1开始,然后到2,但不是回到3,而是回到1,j在1和2之间交换,因此循环无限运行。

Any solutions to this. 任何解决方案。

Thanks. 谢谢。

Your x has only two spaces, but you are writing more characters into it. 您的x只有两个空格,但是您正在向其中写入更多字符。 For example, a 0 in hex is "00" , two characters plus a closing '\\0' . 例如,十六进制的0"00" ,两个字符加一个结束'\\0'
That overwrites neighboring memory, and your j happens to be there and get overwritten. 那会覆盖相邻的内存,而您的j恰好在那里并被覆盖。

Increase the size of x[] , and it should work. 增加x[]的大小,它应该可以工作。

Depending on your values in state[4][4] , you're likely to end up overflowing the x array (remember, you need a place for at most FF (2 chars) + 1 for the terminating '\\0' ). 取决于您在state[4][4] ,您很可能最终会溢出x数组(请记住,您需要一个最多FF (2个字符)+1的位置作为终止'\\0' )。 That's undefined behavior. 那是未定义的行为。 Fix it ( char x[3]; ) and you should be fine. 修复它( char x[3]; ),就可以了。 Here's an mcve : 这是一个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];

You only have two bytes for your "hex output" but no available space for a null character. 您的“十六进制输出”只有两个字节,但没有可用空间用于null字符。

Writing more to an array with lesser capacity is undefined behavior . 向容量较小的数组中写入更多内容是未定义的行为

Increase x array size to 3: x数组大小增加到3:

char x[3];

since as per sprintf : 由于根据sprintf

A terminating null character is automatically appended after the content. 内容后面会自动附加一个终止的空字符。

Thus, you have a total of three characters including the null character. 因此,总共有三个字符, 包括 null字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM