在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]
答案 0 :(得分: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
才能生效。
答案 1 :(得分: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位整数处理它们。
答案 2 :(得分: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;