一、什么是Hex [color=rgba(0, 0, 0, 0.84)]平时我们所看到的数字0-9是十进制,Hex则是0-F十六进制. 二、作用[color=rgba(0, 0, 0, 0.84)]将不可见的十六进制内存数据转换为可显示的字符串 三、代码实现[color=rgba(0, 0, 0, 0.84)]Qt: - QByteArray QByteArray::toHex(char separator) const
- {
- if (!d->size)
- return QByteArray();
- //一个字节会形成两个字符,最终长度是原始数据的2倍
- 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, 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;
- }
- //numbers 0-9 and the letters a-f.
- Q_DECL_CONSTEXPR inline char toHexLower(uint value) Q_DECL_NOTHROW
- {
- // 字符串本身即为指针,相当于数组成员和value进行&操作
- return "0123456789abcdef"[value & 0xF];
- }
复制代码
[color=rgba(0, 0, 0, 0.84)]魔改版: - ByteArray ByteArray::toHex(char separator) const
- {
- if (!m_size)
- {
- return ByteArray();
- }
- const char HEX_NUMBERS[16] = {
- '0', '1', '2', '3',
- '4', '5', '6', '7',
- '8', '9', 'a', 'b',
- 'c', 'd', 'e', 'f' };
- // 一个字节会形成两个字符,最终长度是原始数据的2倍
- const unsigned int length = separator ? (m_size * 3 - 1) : (m_size * 2);
- ByteArray hex;
- hex.resize(length);
- unsigned char* data = (unsigned char*)hex.data();
- for (unsigned int i = 0, o = 0; i < m_size; ++i)
- {
- unsigned char t = reinterpret_cast<unsigned char*>(m_buffer)[i];
- unsigned char high = t / 16;
- unsigned char low = t % 16;
- data[o++] = HEX_NUMBERS[high];
- data[o++] = HEX_NUMBERS[low];
- if (separator && (o < length))
- {
- data[o++] = separator;
- }
- }
- return hex;
- }
复制代码
|