3

在 QT 中,我有一个 qint64。有没有一种简单的方法可以将其分成大小为 int8_t 的部分?

为了清楚起见,如果我有一个

qint64 a = [11001000 00001111 11110000 ... 11001100] 

我想得到

int8_t a1=[11001000] 
int8_t a2=[00001111]
int8_t a3=[11110000] 
... 
int8_t a8=[11001100]
4

3 回答 3

6

这比 Qt 更像是一个 C/C++ 问题。但不管怎么说:

qint64 a = 56747234992934;
union {
    qint64 i64;
    int8_t i8[8];
} u = {a};
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
qDebug() << u.i8[0]; // MSB is the first byte on big endian machines
#else
qDebug() << u.i8[7]; // MSB is the last byte on little endian machines
#endif

编辑:为了避免混乱的字节序特定位置代码:

qint64 a = 56747234992934;
union {
    qint64 i64;
    int8_t i8[8];
} u = {qToBigEndian(a)};
qDebug() << u.i8[0]; // MSB is the first byte on big endian machines

请注意,您需要包含qendian.h此功能才能正常工作。

于 2012-11-12T16:54:38.290 回答
2
int8_t a1 = a & 0xff00000000000000ll >> 56;
int8_t a2 = a & 0x00ff000000000000ll >> 48;
int8_t a3 = a & 0x0000ff0000000000ll >> 40;
int8_t a4 = a & 0x000000ff00000000ll >> 32;
int8_t a5 = a & 0x00000000ff000000ll >> 24;
int8_t a6 = a & 0x0000000000ff0000ll >> 16;
int8_t a7 = a & 0x000000000000ff00ll >> 8;
int8_t a8 = a & 0x00000000000000ffll;

确保附加ll到您的常量,以便以 64 位整数处理它们。

于 2012-11-12T16:32:02.427 回答
1

这是一个破坏性的解决方案。它破坏了a粗心的代码审查者的内容,也许还有一些脑组织。它在美学上也令人愉悦。

int8_t a8 = a;
int8_t a7 = a >>= 8;
int8_t a6 = a >>= 8;
int8_t a5 = a >>= 8;
int8_t a4 = a >>= 8;
int8_t a3 = a >>= 8;
int8_t a2 = a >>= 8;
int8_t a1 = a >>= 8;

一个更好的解决方案,可能在性能和可读性方面并保留以下内容:

int8_t a8 = a;
int8_t a7 = a >> 8;
int8_t a6 = a >> 16;
int8_t a5 = a >> 24;
int8_t a4 = a >> 32;
int8_t a3 = a >> 40;
int8_t a2 = a >> 48;
int8_t a1 = a >> 56;
于 2012-11-12T17:05:11.273 回答