如果我有一个
bitset<16> bits(*iter)
和一个short变量,我该如何将bitset分配给short变量?short myShort = ??bits??
是否可以将 bitset<16> 转换为 short 类型?
bitset<16> bits(*iter)
和一个short变量,我该如何将bitset分配给short变量?short myShort = ??bits??
是否可以将 bitset<16> 转换为 short 类型?
为了避免高位的语言问题,您应该使用无符号短整型。
unsigned short myShort = (unsigned short)bits.to_ulong();
to_ulong
方法,并转换结果(因为你知道只有最低的16位将被使用):short myShort = static_cast<short>( bits.to_ulong() );
to_ulong
可以解决问题。在查看标准C++03 §23.3.5/3之前,我有些怀疑位的顺序是否得到了保证,
因此,您可以将将类bitset的对象转换为某些整数类型的值时,位位置
pos
对应于位值1 << pos
。两个或多个位所对应的整数值是它们的位值之和。
to_ulong
强制转换为unsigned short
(或更好的uint16_t
),而不必担心溢出或字节顺序问题。bitset<16> b;
...
short myShort = (short)b.to_ulong();