Reputation: 11935
if i have a bitset<16> bits(*iter)
and a my short
how i can assign this bist to my short?
short myShort = ??bits??
It's possible to convert a bitset<16> to short?
Upvotes: 6
Views: 2762
Reputation: 137810
As others have said, to_ulong
will work. I was feeling some doubt whether the bit order was guaranteed until I looked at the Standard, C++03 §23.3.5/3,
When converting between an object of class bitset and a value of some integral type, bit position
pos
corresponds to the bit value1 << pos
. The integral value corresponding to two or more bits is the sum of their bit values.
So, you can cast to_ulong
to unsigned short
(or better yet, uint16_t
) with no worries about overflow or endianness.
Upvotes: 2
Reputation: 80
use to_ulong
http://new.cplusplus.com/reference/stl/bitset/to_ulong/
Upvotes: 0
Reputation: 94329
I'd use the to_ulong
method for this, and cast the result (since you know that only the lowest 16 bit will be used):
short myShort = static_cast<short>( bits.to_ulong() );
Upvotes: 2
Reputation: 185852
You really should use an unsigned short, to avoid language quirks on the high bit.
unsigned short myShort = (unsigned short)bits.to_ulong();
Upvotes: 7