PDA

View Full Version : Convert int to hex and placing it in an array of char's



LDS
13th July 2010, 17:45
Hello,

I would like to convert an int number to hex and place it in an array of chars.

Here's the code:


void MainWindow::on_dial_valueChanged(int value)
{
qDebug() << value;
// convert variable value to 0x(value), example value=99 -> new_value = 0x63

char value_to send[11] = {0x01, 0x09, 0x00, 0x13, 0x04, 0x03, 0x20, 0x01, new_value, 0x05, 0x00};
}

Lykurg
13th July 2010, 17:52
Hi,

simply use QString::number() with 16 as base.

LDS
13th July 2010, 18:00
Hello,

but with QString I can't put the number in the char array.



void MainWindow::on_dial_valueChanged(int value)
{
qDebug() << value;
QString new_value = QString().number(value, 16).prepend("0x");
qDebug() << new_value;
const char value[11] = {0x01, 0x09, 0x00, 0x13, 0x04, 0x03, 0x20, 0x01, new_value, 0x05, 0x00}; // error: cannot convert ‘QString’ to ‘const char’ in initialization
}

Lykurg
13th July 2010, 18:16
If you also can use const char * then better use QByteArray and transform it to char with data().

wysota
14th July 2010, 09:39
Modern computers store all numbers in hexadecimal form so there is no point in "converting an integer to hex" because it already is hex.

ChrisW67
15th July 2010, 01:08
LDS, you appear to be thinking of the new_value in:
char value_to send[11] = {0x01, 0x09, 0x00, 0x13, 0x04, 0x03, 0x20, 0x01, new_value, 0x05, 0x00}; as if it were a pre-processor macro expansion rather than the run-time variable use it is. In pre-processing the macro is literally replaced with its value (as if you typed it there) and then the code is compiled: it is a compile time event. What you want is for the value passed in to the function to be placed in the array at run time. There is, as others have pointed out, no need to do anything to value other than check it is a valid character value.


void MainWindow::on_dial_valueChanged(int value)
{
// check that value is in the range 0 to 255 (or -128 to 127) perhaps?
char value_to send[11] = {0x01, 0x09, 0x00, 0x13, 0x04, 0x03, 0x20, 0x01, value, 0x05, 0x00};
// do something with the array before it goes out of scope
}

LDS
16th July 2010, 11:07
Hello,

yes, I was confusing both.
I managed to get the "job" done.
I did the math with the chars instead of converting to int's.


...
char device_value[11] = {0x01, 0x09, 0x00, 0x13, 0x04, 0x03, 0x20, 0x01, 0x00, 0x05, 0xFF};;
int size = sizeof(device_value);

device_value[8] = value;

result = 0xFF ^ device_value[1]; // first value
for (i=2; i < 10; i++)
{
result ^= device_value[i];
}
qDebug("\nfirst checksum: %x\n", result);

device_value[10] = result;
qDebug("value8=%x\n", device_value[8]);
...


Thanks everybody for helping me.
This thread can be marked as solved.

Best regards,
LDS