Safari
Safari

Reputation: 11935

How can i convert bitset into short in c++?

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

Answers (5)

Potatoswatter
Potatoswatter

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 value 1 << 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

l33t
l33t

Reputation: 19937

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

Upvotes: 0

Frerich Raabe
Frerich Raabe

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

Marcelo Cantos
Marcelo Cantos

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

Related Questions