Solved QByteArray to qlonglong
-
What am I doing wrong? I am parsing a binary file, reading 4 bytes at the current position in the file:
QByteArray seconds(playback_file.read(4));
This appears to work correctly in that the bytes in the array match the file:
seconds "\022$uX" QByteArray [0] 18 0x12 char [1] '$' 36 0x24 char [2] 'u' 117 0x75 char [3] 'X' 88 0x58 char
This is from my hex dump of the file at the same spot (pos 8-11):
61 6f 70 20 01 01 20 20 12 24 75 58 40 b7 03 20
However, when I try to convert the array to a qlonglong, it fails:
bool ok; qlonglong ll_seconds = seconds.toLongLong(&ok, 16); Locals ll_seconds 0 int64 ok false bool seconds "\022$uX" QByteArray
-
toLongLong
is not for byte mangling. It interprets the bytes as characters of a string i.e. it would convert a string"123"
into an integer123
.
If you want to just use the bytes directly use the bytes directly:qlonglong foo = *reinterpret_cast<const qlonglong*>(seconds.constData());
Note that you might have to reverse the array first, depending on your data format and executable endianness. For platform independent format you might want to take a look at QDataStream.
-
@Chris-Kawa said in QByteArray to qlonglong:
toLongLong
is not for byte mangling. It interprets the bytes as characters of a string i.e. it would convert a string"123"
into an integer123
.
If you want to just use the bytes directly use the bytes directly:qlonglong foo = *reinterpret_cast<const qlonglong*>(seconds.constData());
Note that you might have to reverse the array first, depending on your data format and executable endianness. For platform independent format you might want to take a look at QDataStream.
Thanks! I might have missed something but it wasn't obvious to me from the documentation that there was an assumption of string format in those QByteArray functions. It seems a bit counter-intuitive.
I switched it to use the QDataStream and its working fine now. I don't have an endianness concern right now, but who knows where this tool will be used in the future.
-
Yeah, for better or worse QByteArray has grown to be kind of a "safer const char*" in that it's not only for storing bytes, as the name would suggest, but also provides a variety of functions that you would expect from a string handling class. It's in the docs
QByteArray can be used to store both raw bytes (including '\0's) and traditional 8-bit '\0'-terminated strings. Using QByteArray is much more convenient than using const char *. Behind the scenes, it always ensures that the data is followed by a '\0' terminator, and uses implicit sharing (copy-on-write) to reduce memory usage and avoid needless copying of data.
but I do think it has grabbed more functionality than it should. Oh well...