PDA

View Full Version : int to char conversion



cooper
14th June 2011, 01:50
Hi everyone,

I am writing a program in Qt to send strings to mini panel printer through serial port.
the panel printer only accept hex code.
so, in my program, i have a function to send command to printer as follow:


ls.append(0x1B + 0x27 + 0x00 + 0x0D);
strSend(ls);

I have some parameters (int values) need to send to printer as well.
for example, i have:
int a = 3;
int b = 53;
I want to convert them to 0x03 and 0x35, and store in a_char and b_char. then i can do:


ls.append(0x1B + 0x27 + 0x00 + 0x0D + a_char + b_char);
strSend(ls);


I saw someone in this forum mentioned about itoa (a,b,16), but Qt gave me error message

error: ‘itoa’ was not declared in this scope
(I did include the stdlib.h)

Can anyone else give me a hint please?
Thanks in advance.

ChrisW67
14th June 2011, 02:34
the panel printer only accept hex code.
The panel accepts a series of bytes. For your convenience you can express them in decimal, hexadecimal, octal, or ASCII characters in your source code. The panel doesn't care, it just accepts the bytes.

You don't tell us what type 'ls' is, but QByteArray is probably the best match for your task.

#include <QtCore>

int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);

int a = 3;
int b = 53;

QByteArray ls;
ls += 0x1b; // hex
ls += 39; // decimal
ls += '\0'; // as a character
ls += 015; // octal
ls += static_cast<char>(a); // explicit cast from int
ls += b; // implicit cast from int
// send the byte array

qDebug() << ls.toHex();

return 0;
}

You could more conveniently initialise the fixed data in the array like:


QByteArray ls = QByteArray::fromHex("1b27000d");

then append a and b.

cooper
14th June 2011, 03:41
Hi ChrisW67,

Thanks for your quick reply. I will try it.
One more question. if i want to send a string to printer, do i just do



...
ls += 'my string';
...


I really appreciate your help.

ChrisW67
14th June 2011, 04:50
That won't compile, or won't work if it does. Try double quotes: single quotes are for character literals.

Does your printer take ASCII only, or does it do Unicode through UTF-8? If it does do Unicode then using QString to build your output and then toUtf8() might also work.