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.
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());
static_cast the code is more resilient to someone coming in and changing types. 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.#include <bitset>
#include <iostream>
template<std::size_t SIZE>
int bitSetToInt(std::bitset<SIZE> bitSet) {
if (!bitSet[SIZE - 1]) return bitSet.to_ulong();
bitSet.flip();
return -(bitSet.to_ulong() + 1);
}
int main() {
std::bitset<31> bitSet1(7);
std::bitset<31> bitSet2(-7);
std::bitset<32> bitSet3(7);
std::bitset<32> bitSet4(-7);
std::cout << bitSet1 << " = " << bitSetToInt(bitSet1) << std::endl;
std::cout << bitSet2 << " = " << bitSetToInt(bitSet2) << std::endl;
std::cout << bitSet3 << " = " << bitSetToInt(bitSet3) << std::endl;
std::cout << bitSet4 << " = " << bitSetToInt(bitSet4) << std::endl;
}
0000000000000000000000000000111 = 7
1111111111111111111111111111001 = -7
00000000000000000000000000000111 = 7
11111111111111111111111111111001 = -7
#include <iostream>
#include <boost/dynamic_bitset.hpp>
int dynamicBitSetToInt(boost::dynamic_bitset<> bitSet) {
if (!bitSet[bitSet.size() - 1]) return (int) bitSet.to_ulong();
bitSet.flip();
return (int) -(bitSet.to_ulong() + 1);
}
int main() {
boost::dynamic_bitset bitSet1(31, 7);
boost::dynamic_bitset bitSet2(31, -7);
boost::dynamic_bitset bitSet3(32, 7);
boost::dynamic_bitset bitSet4(32, -7);
std::cout << bitSet1 << " = " << dynamicBitSetToInt(bitSet1) << std::endl;
std::cout << bitSet2 << " = " << dynamicBitSetToInt(bitSet2) << std::endl;
std::cout << bitSet3 << " = " << dynamicBitSetToInt(bitSet3) << std::endl;
std::cout << bitSet4 << " = " << dynamicBitSetToInt(bitSet4) << std::endl;
}
std::bitsethas 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?ulongtolong, theninti.e.int(long(mybit.to_ulong()))