diff options
author | Andre Hartmann <aha_1980@gmx.de> | 2012-07-07 18:11:00 +0200 |
---|---|---|
committer | André Hartmann <aha_1980@gmx.de> | 2016-12-24 21:05:43 +0000 |
commit | 615027129d3d5e12a6e2f5d02d2af8320cc58ea7 (patch) | |
tree | 53bfdc8d0c1742dd7f416854f9eeaed6ef2ab029 /src/corelib/tools/qbytearray.cpp | |
parent | 8266de089cdc85a5ac93361e22722ba817878c4b (diff) |
QByteArray: Overload toHex() with separator character
The separator character is inserted in the resulting array
after every byte and is useful for MAC address output like
01:23:45:ab:cd:ef, Hash fingerprints, or low level data
debug output.
[ChangeLog][QtCore][QByteArray] Added toHex() overload to
insert a separator character between the hex bytes.
Change-Id: Ibe436094badc02f3ade7751aa8b5d690599941d4
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Diffstat (limited to 'src/corelib/tools/qbytearray.cpp')
-rw-r--r-- | src/corelib/tools/qbytearray.cpp | 37 |
1 files changed, 33 insertions, 4 deletions
diff --git a/src/corelib/tools/qbytearray.cpp b/src/corelib/tools/qbytearray.cpp index 7d9c5dc325..82c88ca694 100644 --- a/src/corelib/tools/qbytearray.cpp +++ b/src/corelib/tools/qbytearray.cpp @@ -4355,12 +4355,41 @@ QByteArray QByteArray::fromHex(const QByteArray &hexEncoded) */ QByteArray QByteArray::toHex() const { - QByteArray hex(d->size * 2, Qt::Uninitialized); + return toHex('\0'); +} + +/*! \overload + \since 5.9 + + Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and + the letters a-f. + + If \a separator is not '\0', the separator character is inserted between the hex bytes. + + Example: + \code + QByteArray macAddress = QByteArray::fromHex("123456abcdef"); + macAddress.toHex(':'); // returns "12:34:56:ab:cd:ef" + macAddress.toHex(0); // returns "123456abcdef" + \endcode + + \sa fromHex() +*/ +QByteArray QByteArray::toHex(char separator) const +{ + if (!d->size) + return QByteArray(); + + const int length = separator ? (d->size * 3 - 1) : (d->size * 2); + QByteArray hex(length, Qt::Uninitialized); char *hexData = hex.data(); const uchar *data = (const uchar *)d->data(); - for (int i = 0; i < d->size; ++i) { - hexData[i*2] = QtMiscUtils::toHexLower(data[i] >> 4); - hexData[i*2+1] = QtMiscUtils::toHexLower(data[i] & 0xf); + for (int i = 0, o = 0; i < d->size; ++i) { + hexData[o++] = QtMiscUtils::toHexLower(data[i] >> 4); + hexData[o++] = QtMiscUtils::toHexLower(data[i] & 0xf); + + if ((separator) && (o < length)) + hexData[o++] = separator; } return hex; } |