Search code examples
c++binarysignedbitset

Bitset and signed values


I am using std::bitset to convert a decimal value to its binary representation, but I am not sure if bitset handles signed values or not.

For example, bitset<10>(5) gives you 0000000101. But what if its bitset<10>(-5)?

Here is my code in specific:

while (getline(ss, token, ',')){
    ss.ignore();
    myString.push_back(token);
}
myString[0].erase(0, 1);
myString[1].erase(0, 1);
rt = bitset<7>(stoi(myString[0])).to_string();
ra = bitset<7>(stoi(myString[1])).to_string();
i10 = bitset<10>(stoi(myString[2])).to_string();

and the i10 should be signed. Will my current code handle signed values? myString will hold the decimal representation that is input by a user, but i need to do some concatenating and writing to a file so im converting to strings for ease.


Solution

  • bitset doesn't handle signed-ness itself. The constructor you're calling takes an unsigned integer. From [bitset.cons]:

    constexpr bitset(unsigned long long val) noexcept;
    

    Effects: Constructs an object of class bitset<N>, initializing the first M bit positions to the corresponding bit values in val. M is the smaller of N and the number of bits in the value representation (3.9) of unsigned long long. If M < N, the remaining bit positions are initialized to zero.

    So if you call it with -5, that gets converted to unsigned long long as 0xfffffffffffffffb. The bottom 10 bits of that are 0x3fb, which is the set you get. But it's unsigned. Both conversion functions give you back an unsigned value (from [bitset.members]):

    unsigned long to_ulong() const;
    unsigned long long to_ullong() const;
    

    All of which is to say - a bitset is a set of bits. It doesn't have a sign. The first bit isn't special - it's just another bit.