Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[solved] QString to QByteArray



  • Hi,

    what is the most efficient (speed) way to convert a QString
    @"AA 0D 00 FF 0A 00 00 00 FF FF FF FF 00 00"@

    (including SPACEs )

    to a QByteArray conatinig the above data as:

    @0xAA, 0x0D, 0x00, .... , 0xFF, 0x00, 0x00 @

    thx


  • Lifetime Qt Champion

    Hi,

    You'll have to do some benchmarking.

    @
    QRegularExpression rx("([A-F0-9]{2})");
    text.replace(rx , "0x\1," ).chop(1);
    qDebug() << text.toLatin1();
    @

    is a possibility

    [edit: updated code to avoid strange replacement]



  • Hello SGaist,

    your suggestion looks faster than mine, but i can not use it as it.
    Got @error: 'QRegular' was not declared in this scope@
    I included
    @#include <QRegularExpression>
    #include <QRegExp>

    ... QRegular[removed] ... // <
    @

    here is my first trial:
    @ int i;
    QByteArray ba_frag;
    for(i=0;i<text1.size();i+=3) {
    ba_frag.append(QByteArray::fromHex((text1.mid(i,2)).toLatin1()));
    }
    @
    above seems to work


  • Moderators

    Hi,

    fromHex() already handles spaces. Just call
    @
    QByteArray ba_frag = QByteArray::fromHex(text1.toLatin1());
    @

    [quote author="SGaist" date="1424034271"]
    @
    text.replace(QRegular[removed]"([A-F0-9]{2})"), "0x\1,").chop(1);
    @
    [/quote]Did the forum censor you??


  • Lifetime Qt Champion

    It seems that Expression followed by ( triggers [removed]



  • hm, ?


  • Moderators

    [quote author="wally123" date="1424157850"]hm, ?[/quote]SGaist typed
    @
    QRegularExpressionn("([A-F0-9]{2})")
    // Remove the extra 'n' above
    @

    but it got converted to...
    @
    QRegular[removed]"([A-F0-9]{2})")
    @
    ...by forum security.



  • Ah, ok :)


Log in to reply