简体   繁体   中英

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() .

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.

Any solutions to this.

Thanks.

Your x has only two spaces, but you are writing more characters into it. For example, a 0 in hex is "00" , two characters plus a closing '\\0' .
That overwrites neighboring memory, and your j happens to be there and get overwritten.

Increase the size of x[] , and it should work.

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' ). That's undefined behavior. Fix it ( char x[3]; ) and you should be fine. Here's an 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.

Writing more to an array with lesser capacity is undefined behavior .

Increase x array size to 3:

char x[3];

since as per sprintf :

A terminating null character is automatically appended after the content.

Thus, you have a total of three characters including the null character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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