My Qt function works as not expected [solved]
-
Hi!
I have to convert some symbols have been read from textInput to hex string.
Where I was debugging, I use that code in formData() method - it works good:
@void MainWindow::formData(){
QByteArray text_data = ui->lineEdit->text().toLocal8Bit(), data_to_write;
char buf[2];
unsigned int mByte;
for(int pos = 0, i=0; pos<text_data.length(); pos+=2, i++){
buf[0]=text_data[pos];
buf[1]=text_data[pos+1];
sscanf(buf, "%x", &mByte);
data_to_write[i] = mByte;
};
emit formed(data_to_write);
}@My sscanf(buf, "%x", &mByte); fragment for buf={'F', 'E'} returns to mByte 254 value as I expected.
But when I wrote method to do this from a lot of places of my program - it returns 4068 value. Here is code of my methods:
@void MainWindow::formData(){
QByteArray text_data = ui->lineEdit->text().toLocal8Bit(), data_to_write;
data_to_write = convertToHexArray(text_data);
emit formed(data_to_write);
}QByteArray MainWindow::convertToHexArray(QByteArray input){
QByteArray data_to_write;
char buf[2];
unsigned int mByte;
for(int pos = 0, i=0; pos<input.length(); pos+=2, i++){
buf[0]=input[pos];
buf[1]=input[pos+1];
sscanf(buf, "%x", &mByte);
data_to_write[i] = mByte;
};
return data_to_write;
}@So, in second occurence sscanf returns 4068. Debugger shows that buf variable is same in both occasions.
Why??? -
Hi,
Maybe a silly question but why don't you just use "QByteArray::toHex()":http://qt-project.org/doc/qt-5/qbytearray.html#toHex ?
-
Because it converts each symbol in hex (e.g. 'f', 'e' will equal '46', '45'), but I want to write 254, as 1 byte, as 0xfe.
-
Hi,
Copy the bytes you need into a local ByteArray and then to the toHex. That should give you the total value in hex, not hex for every byte. -
[quote author="Jeroentje@home" date="1395403157"]Hi,
Copy the bytes you need into a local ByteArray and then to the toHex. That should give you the total value in hex, not hex for every byte.[/quote]@QByteArray test = QByteArray("FE");
qDebug()<<test.toHex();@returns 4645
For each symbol. Or I misunderstood you? -
@QByteArray test = QByteArray::fromHex("FE002101");@
Works as I planned. Let's try
-
OKay, problem is solved.
@void MainWindow::formData(){
QByteArray text = ui->lineEdit->text().toLocal8Bit();
QByteArray data_to_write = convertToHexArray(text);
...
@@QByteArray MainWindow::convertToHexArray(QByteArray input){
QByteArray data_to_write = QByteArray::fromHex(input);
return data_to_write;
}@ -
Thanks for sharing your solution.
Also, could you edit the title of your first post an add [solved]
This way helpfull minds know it 's already solved;-)