PDA

View Full Version : Converting from char to byte



Ferric
7th January 2010, 02:18
Hi,

I would like to create a random packet of data, 128 bits long (16bytes).

My basic idea is to generate 16 pseudo-random numbers (between 0 and 255), then turn each of these numbers into their equivalent bytes. Then I intend to put these 16 bytes end to end to create my packet.

This is what I have so far:



void Loader::calculateRandomCode()
{
int n;
n = qrand() % 255; // limits the random number to between 0 and 255
QString qs = QString::number(n); // converts from int to string
QLabel *label = new QLabel(qs); // prints to screen just so I can see whats going on
label->show(); // prints to screen just so I can see whats going on
}



How do I turn n into a byte?


Thanks for reading

bythos
7th January 2010, 06:47
well a int is 4 bytes long in 32bit architecture and 8 bytes in 64bit architecture so what you should do it instead of using int is try using "unsigned char". and cast the result of qrand to "unsigned char"

unsigned char n;
n = (unsigned char) qrand() % 255;

Tanuki-no Torigava
8th January 2010, 01:27
Did you look at quint8, quint16, quint32 or quint64? You can use quint32[4] to have you 128 bits or quint8[16] to process that byte by byte.