如果我有一个bitset<16> bits(*iter)
和一个我的短裤,我怎么能把这个 bist 分配给我的短裤?
short myShort = ??bits??
可以将 bitset<16> 转换为 short 吗?
如果我有一个bitset<16> bits(*iter)
和一个我的短裤,我怎么能把这个 bist 分配给我的短裤?
short myShort = ??bits??
可以将 bitset<16> 转换为 short 吗?
你真的应该使用无符号短,以避免高位的语言怪癖。
unsigned short myShort = (unsigned short)bits.to_ulong();
正如其他人所说,to_ulong
将工作。在查看标准 C++03 §23.3.5/3 之前,我一直怀疑位顺序是否得到保证,
在类 bitset 的对象和某个整数类型的值之间进行转换时,位位置
pos
对应于位值1 << pos
。两个或多个比特对应的整数值是它们的比特值之和。
因此,您可以to_ulong
转换为unsigned short
(或更好的是uint16_t
),而不必担心溢出或字节序。
我会为此使用该to_ulong
方法,并转换结果(因为您知道只会使用最低 16 位):
short myShort = static_cast<short>( bits.to_ulong() );
bitset<16> b;
...
short myShort = (short)b.to_ulong();