27
votes

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.

1
Convert it to unsigned long, then cast that to int. - Barmar
As the documentation says, std::bitset has function to convert the value to a ulong. So as @Barmar says, cast that long to a int. So whats your problem? Have you readed the documentation or tried anything before posting the question? - Manu343726
@Johnsyweb He probably wants to handle negative values, as his example shows. - Kaidjin
Convert that ulong to long, then int i.e. int(long(mybit.to_ulong())) - Erkin Alp Güney

1 Answers

55
votes

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