PDA

View Full Version : newbie - int to char* and more.



rebelo55
20th May 2015, 17:11
Hello,

I am new to QT on Linux. I've been a .NET programmer and now working on Beaglebone Black. I'm using C++ to communicate with a motor controller which requires a command's parameter to be sent one byte at a time.

My function receives an int (decimal) and this needs to be converted to Hex and then sent to another function one byte at a time.
For example,

Function parameter -> 16000 (decimal)
convert it to Hex -> 3E80
format the number as 000000 -> 003E80
now this number must be sent one byte at a time so it must be broken down like this:
char x[3];
x[0] = 0x00;
x[1] = 0x3E;
x[2] = 0x80;

How can I achieve this? Sorry I'm a real newbie in C++/QT.

Thanks

d_stranz
20th May 2015, 21:31
This is C++ 101. You should be able to use a union for this:


union myConverter
{
std::uint32_t intVal;
unsigned char[4] charVal;
}

myConverter c;
c.intVal = 16000;

// c.charVal[0] - [3] now contains the unsigned hex values


Of course, this assumes you have the same byte order on your target device. If not, you'll need to swap bytes around.

ChrisW67
20th May 2015, 21:53
Or something like this


quint32 value = 16000; // or 0x00003e80
char x[3];
x[0] = (value >> 16) & 0xff ;
x[1] = (value >> 8) & 0xff ;
x[2] = value & 0xff ;


The question really has nothing to do with hex, which is a human friendly string representation of a binary value.

rebelo55
20th May 2015, 23:36
Both the solutions worked. thanks experts!!:):):)