Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert bitset to int in c++

Tags:

In c++. I initialize a bitset to -3 like:

std::bitset<32> mybit(-3); 

Is there a grace way that convert mybit to -3. Beacause bitset object only have methods like to_ulong and to_string.

like image 676
tenos Avatar asked Oct 25 '13 07:10

tenos


People also ask

What is BitSet in C?

Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.

How do you reverse a BitSet?

bitset::flip() in C++ STL It flips the bits of the calling bitset. This method flips all 0's to 1's and all 1's to 0's, which means it reverse each and every bit of the calling bitset when no parameter is passed. If a parameter is passed the flip method will flip only the nth bit for the integer n passed.

What is BitSet size?

size() method returns the number of bits of space actually in use by this BitSet to represent bit values. The maximum element in the set is the size - 1st element.

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


1 Answers

Use to_ulong to convert it to unsigned long, then an ordinary cast to convert it to int.

int mybit_int;  mybit_int = (int)(mybit.to_ulong()); 

DEMO

like image 84
Barmar Avatar answered Sep 26 '22 21:09

Barmar