![](/img/trans.png)
[英]Qt: save QPixmap to std::vector<unsigned char> - or convert QByteArray to std::vector<unsigned char>
[英]Convert QByteArray to std::vector<unsigned char>
我嘗試使用以下代碼將QByteArray
轉換為std::vector<unsigned char>
:
unsigned char* buffer = (unsigned char*)byteArrayBuffer.constData();
std::vector<unsigned char>::size_type size = strlen((const char*)buffer);
std::vector<unsigned char> bufferToCompress(buffer, buffer + size);
但是,假設byteArrayBuffer
是一個填充數據的QByteArray
,我認為它在行unsigned char* buffer = (unsigned char*)byteArrayBuffer.constData();
因為byteArrayBuffer.size()
返回的值不同於byteArrayBuffer.size()
bufferToCompress.size()
。
我怎樣才能讓它運轉起來?
我不熟悉Qt,但你肯定只想要
std::vector<unsigned char> bufferToCompress(
byteArrayBuffer.begin(), byteArrayBuffer.end());
注意: strlen
在C ++中不是特別有用; 它會告訴你一個C風格的以空字符結尾的字符串的長度(通過搜索內存,直到它找到一個零值字節,或者從可訪問內存的末尾掉落並崩潰),但不能告訴你它的大小一個數組,這是你在這里需要的。 此外,使用邪惡的C風格強制轉換來強制編譯無效代碼永遠不是一個好主意。
正如我在這里看到的那樣http://qt-project.org/doc/qt-4.8/qbytearray.html QByteArray沒有開始/結束方法。 但有數據/長度。 結果代碼可能如下所示:
const unsigned char* begin = reinterpret_cast<unsigned char*>(byteArrayBuffer.data());
const unsigned char* end = begin + byteArrayBuffer.length();
std::vector<unsigned char> bufferToCompress( begin, end );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.