Dynamic cast



  • Hi,

    I am new to QT. Was trying an option in a tool which receives a set of variables and a file that has info about their data types. If i need to store and display them, which is the best way to dynamically cast.
    For example:
    If i receive 4 bytes which has 3 variables A(qint16) B(quint8) C(qint8)
    say i define a qint64 val;
    val = (dynamic casting) A/B/C ;
    Is there a better way other than check the data type and use switch-case to cast it i.e
    if (data_type == "quint16") { val = (quint16)data; } etc...



  • From "this doc":http://www.cplusplus.com/doc/tutorial/typecasting/#dynamic_cast
    "dynamic_cast can only be used with pointers and references to classes (or with void*)."

    So dynamic_cats will not work for the integers.
    If you need to convert a bunch of bytes into integer then you need to know what kind of integer you will use. Which makes it impossible to avoid some kind of if/else or switch statement. You can hide it but I don't any other way to convert the bytes to the integer.

    Or I'm totally misunderstood your question :-)



  • Instead of dynamic_cast you can use the old school solution: a union
    for example:
    @union
    {
    qint32 v32;
    struct
    {
    qint16 v16A;
    qint16 v16B;
    } v16;
    struct
    {
    qint8 V8A;
    qint8 V8B;
    qint8 V8C;
    qint8 V8D;
    } v8;
    } receivedblob; @

    So for example:
    receivedblob.v32 = received4bytes();

    receivedblob.v16.v16a will now read the same bits as receivedblob.v8.V8A and V8B, and of course receivedblob.v32 lower half :-)



  • Thanks! With unsigned int options there would be many combinations in union. I shall go with switch case option.


Log in to reply
 

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