Results 1 to 2 of 2

Thread: Converting from char* to QByteArray does not work

  1. #1
    Join Date
    Feb 2016
    Posts
    7
    Thanks
    1
    Qt products
    Qt5
    Platforms
    Windows

    Default Re: Converting from char* to QByteArray does not work

    Hello,
    I have a char* that holds 256 chars. I can not convert it to QByteArray. My char* contains following data: 0xff, 0xff, 0xff, 0xff, 0xaa, 0x99, 0x55, 0x66, 0x31, 0x61, 0x00, 0x00, 0x32, 0x81,.....
    Qt Code:
    1. QByteArray b1, b2;
    2. char *data = (char *)malloc(256 * sizeof(char));
    3. FLASH_ReadCalibration(CALIBRATION_ADDR, data);
    4. b1 = QByteArray::fromRawData((const char*)data, sizeof(data));
    5. b2 = QByteArray(reinterpret_cast<const char*>(data), sizeof(data));
    6. emit updateData(ByteData);
    To copy to clipboard, switch view to plain text mode 

    b1 and b2 contain only 4 bytes: 0xff, 0xff, 0xff, 0xff

    What is wrong with my code?
    Thanks.


    Added after 25 minutes:


    I have found it. sizeof(data) returns 4, although data contains 256 chars.
    This worked: b1 = QByteArray::fromRawData((const char*)data, 256);
    Last edited by kahlenberg; 4th February 2016 at 16:14.

  2. #2
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,419
    Thanks
    37
    Thanked 1,545 Times in 1,495 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: Converting from char* to QByteArray does not work

    Quote Originally Posted by kahlenberg View Post
    I have found it. sizeof(data) returns 4, although data contains 256 chars.
    data is a pointer (to char), a pointer's size on a 32bit machine is 32bit (4 bytes), on a 64bit machine 64bits (8 bytes)

    For your use case the best apprioach would be to create a QByteArray of the appropriate size and hand its buffer over to the C function.
    That avoids copying the data and having to manually free the memory.

    Cheers,
    _

Similar Threads

  1. converting qstring to unsigned char
    By havij000 in forum Qt Programming
    Replies: 1
    Last Post: 22nd July 2013, 07:36
  2. Converting from char to byte
    By Ferric in forum Newbie
    Replies: 2
    Last Post: 8th January 2010, 00:27
  3. Converting QString to char* in onl line
    By hubbobubbo in forum Qt Programming
    Replies: 10
    Last Post: 11th December 2009, 11:45
  4. Converting QString to char array
    By srohit24 in forum Qt Programming
    Replies: 3
    Last Post: 22nd July 2009, 18:19
  5. QString to char* not converting
    By DPinLV in forum Qt Programming
    Replies: 17
    Last Post: 6th August 2006, 12:15

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.