27

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.

Barmar
  • 669,327
  • 51
  • 454
  • 560
tenos
  • 849
  • 1
  • 9
  • 16
  • 2
    Convert it to unsigned long, then cast that to int. – Barmar Oct 25 '13 at 07:31
  • As [the documentation says](http://en.cppreference.com/w/cpp/utility/bitset), `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 Oct 25 '13 at 07:38
  • 1
    @Johnsyweb He probably wants to handle negative values, as his example shows. – Kaidjin Oct 25 '13 at 07:51
  • Convert that `ulong` to `long`, then `int` i.e. `int(long(mybit.to_ulong()))` – Erkin Alp Güney Dec 09 '16 at 19:04

1 Answers1

54

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

Barmar
  • 669,327
  • 51
  • 454
  • 560
  • 26
    As this is C++ I would suggest using [static_cast(mybit.to_ulong())](http://stackoverflow.com/questions/103512/in-c-why-use-static-castintx-instead-of-intx) rather than a C-style cast. – Steve Oct 25 '13 at 08:01
  • 2
    not working, still spitting out unsigned integer. -3 is becoming 251 – FluorescentGreen5 Aug 05 '16 at 09:11
  • @FluorescentGreen5 I've added a demo showing that it works. – Barmar Aug 05 '16 at 13:08
  • @Barmar oh, i used <8> instead of <32> cutting of the signature – FluorescentGreen5 Aug 05 '16 at 13:51
  • @Steve: Primitive types have no difference in static(C-style cast is also static) and dynamic casts. Only `reinterpret_cast` is different for them. – Erkin Alp Güney Dec 09 '16 at 19:07
  • 1
    @ErkinAlpGüney I think his suggestion is about style -- in C++ you should use the template syntax rather than the C syntax for casts, because it makes your intent clearer. But I'm not that much of a purist, and I find the verbose syntax off-putting. – Barmar Dec 09 '16 at 19:40
  • 2
    @ErkinAlpGüney - my suggestion is about safety of the operation. If you use a `static_cast` the code is more resilient to someone coming in and changing types. http://stackoverflow.com/a/103868/1517648 I've seen various occasions where C-style casts were ok, until someone changed something and then they weren't. A `static_cast` would pick this up with a compiler error. – Steve Jan 12 '17 at 21:19