How to store random number in usigned char variable in c++?

84 views Asked by At

I am wanting to fill a unsigned char 2d array with random 8 bit hex numbers using rand(). But I am getting weird results(seen below) when I try to save them in my array. It works fine if I change the 2d array to an int array, but I really wanna keep unsigned char so I know only numbers that are 8 bit can be saved into each index. Here is the code I was testing on:

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand(time(NULL));

    unsigned char key[4][4];

    for (int y = 0; y < 4; y++) 
    {
        for (int x = 0; x < 4; x++)
        {
            key[x][y] = (rand() % 256);
            cout << hex << setfill('0') << setw(2) << key[x][y] << " | ";
        }
        cout << endl;
    }

}

Is there any solution to this? Or is there a better way to fill my 2d array with random 8bit numbers?

To clarify weird results, this is what I get:

0┘ | 0☻ | 0| | 0┌ |
0L | 0ä | 0⌐ | 0ä |
0☺ | 0î | 0X | 0Y |
0▬ | 0╧ | 0@ | 0╩ |
1

There are 1 answers

2
Lachlan On

Need to cast key[x][y] as int or unsigned, for example:

cout << hex << setfill('0') << setw(2) << (unsigned)key[x][y] << " | ";

or

cout << hex << setfill('0') << setw(2) << int(key[x][y]) << " | ";

As answered by John and Tadman