QString to quint8 array



  • Hi, I have a QString like this: "254 28 0 1 147 155 12 36 74 0 0 14 23".
    I've managed to convert the string to a quint8 array splitting the string and converting each character individually but this method is quite slow. I'm sure there's a faster and smarter way of doing it but I haven't found it yet. ¿How could I achieve this?

    Thanks in advance!


  • Moderators

    Hi,

    [quote]I’ve managed to convert the string to a quint8 array splitting the string and converting each character individually[/quote]You don't need to convert each character individually.

    Call QString::split(), then

    Call QString::toUInt() or QString::toUShort() (then cast the result to quint8)

    Documentation: http://qt-project.org/doc/qt-5/qstring.html



  • Sorry, I don't understand you. I think that's what I'm doing actually.

    @lineReplay = streamReplayLog.readLine();
    sizRead = lineReplay.count(' ');
    listReplay = lineReplay.split(" ");
    for (int i = 0; i < sizRead; i++)
    {
    buffRead[i] = listReplay[i].toUInt();
    }@

    That works but it seems to me that it is a little slow.

    Thanks!


  • Moderators

    Yes, that's what I meant.

    How slow is it? How long is lineReplay?

    You can speed it up a bit by removing lineReplay.count(). Just use
    @for (int i = 0; i < listReplay.count(); ++i)@

    By the way, your current code misses the last number. Your loop should check i <= sizRead, not i < sizRead

    Also, how do you set the size of buffRead?


  • Moderators

    I've hit this kind of problem a few times when writing parser for "big" files like 3d object files.
    Profiling revealed that the problem is with the split method. If the line has like 1000 entries it creates 1000 instances of very small strings just to be discarded by you a line or two later. This is very memory/cache unfriendly and thus slow.

    The way I managed to optimize this is by not splitting the string at all. Instead you can use a QStringRef, which is just a stack based wrapper object around QString and use the indexOf functions to find next numbers. It's a lot faster because it doesn't involve any memory copies or dynamic allocation.



  • Thanks. QStringRef seems to work a little faster.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.