View Full Version : Convert int to hex and add to char array to send to serial port

15th July 2015, 17:25
Hello everyone, I'm sorry if this had been asked but I couldn't find anything in the forum like this.

So let's say I have an array of char like this:

char thd[] = {0x01, 0x07, 0x02, value, 0x00, 0x6E, 0x04}

I make a Qlineedit that gets user input of an integer from 0 -> 255. For instance, the user will input 100.

How do I take that 100 and turn it into 0x64 and put that into the place of "value" to send the char array to the serial port. I've tried QString::number to convert it to int but I get stuck there because I can't figure out how to add the "0x" in front of it and add it to the array.

I will appreciate any attempt of helping. Thank you.

15th July 2015, 17:47
I've tried QString::number to convert it

You mean QString::toInt()?

I can't figure out how to add the "0x" in front of it

You don't need to do that. The 0x is only telling the compiler that the following sequence of characters is to be intereted as a hex number (integer number with base 16).

and add it to the array.

If I understand your array correctly, you want to write the value to the fourth position.
Arrays allow direct access to all their fields by numerical index, starting at 0. The fourth field is therefore thd[3]

15th July 2015, 18:13
Yes sorry, I meant to say QString::toInt, and thank you, I figure out my problem. I initialized a QString type for QString::toInt instead of an integer type and that's why I couldn't add it to the char array. And I always thought that I needed to add the "0x" in front and therefore it didn't work. This thread can be marked as solved now :).