Десериализация QByteArray с известным QMetaType :: Type в QVariant - PullRequest
1 голос
/ 07 августа 2020

У меня есть QByteArray, содержащий необработанные данные переменной. QMetaType::Type, описывающий переменную, известен.

Я хочу десериализовать эту переменную в QVariant

со следующими входными данными:

QByteArray bytes; // Consider it initialized
QMetaType::Type type; // Same

Мои попытки так далеко не работают:

QVariant var{bytes};
var.convert(type); // Does not work, apparently QVariant expects bytes to be a string representation of the variable
QDataStream ds(bytes, QIODevice::ReadOnly);
QVariant var;
ds >> var; // Does not work because bytes does not come from the serialization of a QVariant (especially, it lacks type information)

Я не могу изменить свои типы входов или выходов:

  • Входы должны иметь тип QByteArray и QMetaType::Type.
  • Вывод должен иметь тип QVariant

Пример:

//Inputs
QByteArray bytes = { 0x12, 0x34, 0x56, 0x78 };
QMetaType::Type type = QMetaType::UInt; // Suppose the size of unsigned int is 4 bytes (could be 2)
// Note: this is an example, in pratice I have to manage many types, including double

//Expected output:
QVariant var = deserialize(bytes, type);
// var.type() == QMetaType::UInt
// var.toUInt() == 305419896 (== 0x12345678)

1 Ответ

0 голосов
/ 07 августа 2020

Вы можете записать в unsigned int, а затем преобразовать его в QVariant:

    const char data[] = { 0x12, 0x34, 0x56, 0x78 };
    QByteArray bytes { QByteArray::fromRawData( data, 4) };

    QDataStream s {&bytes, QIODevice::ReadOnly};
    //write out the data to uint
    unsigned int x{};
    s >> x;

    //create a Qvariant from it
    QVariant var{x};

    qDebug () << "x: " << x;                       //305419896
    qDebug () << "variant: " << var;               //QVariant(uint, 305419896)
    qDebug () << "variant uint: " << var.toUInt(); //305419896

В качестве альтернативы вы также можете напрямую создать QVariant:

    auto v = QVariant(bytes.toHex().toUInt());
    //auto v = QVariant(bytes.toUInt());            //this will not work
    qDebug () << "Bytes to uint; " << v.toUInt(); //305419896
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...