Results 1 to 3 of 3

Thread: storing integer 4bytes in QByteArray

  1. #1
    Join Date
    Nov 2007
    Posts
    291
    Thanks
    85
    Thanked 1 Time in 1 Post

    Default storing integer 4bytes in QByteArray

    hi
    i want to store the integers in QByteArray as raw bytes.but the QByteArray converts it to character and then stores.
    Qt Code:
    1. ba.append(QByteArray::number((qint32)50));
    2. qDebug()<<ba.size();//Prints 2 (i expect the size of qint32. ie.4)
    To copy to clipboard, switch view to plain text mode 

    How to store integer as raw bytes.

    Thank u

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,359
    Thanks
    3
    Thanked 5,015 Times in 4,792 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: storing integer 4bytes in QByteArray

    If you use QByteArray::number then your number gets converted to string, I don't see anything unusual in getting the size of the resulting array as 2 (characters "5" and "0"). If you want to store the hex values of each byte of the variable then either use memcpy() or copy values byte by byte into the array.

  3. The following user says thank you to wysota for this useful post:

    babu198649 (30th November 2008)

  4. #3
    Join Date
    May 2008
    Posts
    155
    Thanked 15 Times in 13 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11

    Default Re: storing integer 4bytes in QByteArray

    Quote Originally Posted by babu198649 View Post
    hi
    i want to store the integers in QByteArray as raw bytes.but the QByteArray converts it to character and then stores.
    Qt Code:
    1. ba.append(QByteArray::number((qint32)50));
    2. qDebug()<<ba.size();//Prints 2 (i expect the size of qint32. ie.4)
    To copy to clipboard, switch view to plain text mode 
    How to store integer as raw bytes.

    Thank u
    The following might do the trick:

    Qt Code:
    1. quint32 number = 50;
    2. QByteArray ba((const char *)&number, sizeof(number));
    To copy to clipboard, switch view to plain text mode 

    Note the result depends on the endian-ness of your machine and using a C++ cast instead of the C cast might be more appropriare.

  5. The following 2 users say thank you to ktk for this useful post:

    babu198649 (30th November 2008), SIFE (9th June 2011)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.