如何在C++中将bitset转换为short?

6
如果我有一个bitset<16> bits(*iter)和一个short变量,我该如何将bitset分配给short变量?
short myShort = ??bits??

是否可以将 bitset<16> 转换为 short 类型?

5个回答

7

为了避免高位的语言问题,您应该使用无符号短整型。

unsigned short myShort = (unsigned short)bits.to_ulong();

2
我会使用to_ulong方法,并转换结果(因为你知道只有最低的16位将被使用):
short myShort = static_cast<short>( bits.to_ulong() );

2
正如其他人所说,to_ulong可以解决问题。在查看标准C++03 §23.3.5/3之前,我有些怀疑位的顺序是否得到了保证,

将类bitset的对象转换为某些整数类型的值时,位位置pos对应于位值1 << pos。两个或多个位所对应的整数值是它们的位值之和。

因此,您可以将to_ulong强制转换为unsigned short(或更好的uint16_t),而不必担心溢出或字节顺序问题。


0
bitset<16> b;
...   
short myShort = (short)b.to_ulong();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接