vendredi 29 septembre 2017

difference in output using std::size_t and std::bitset for bit operations

Having following code:

#include <iostream>
#include <bitset>
#include <limits>
#include <limits.h>
using namespace std;

constexpr std::size_t maxBits = CHAR_BIT * sizeof(std::size_t);

int main() {
    std::size_t value =47;
    unsigned int begin=0;
    unsigned int end=32;

    //std::size_t allBitsSet(std::numeric_limits<std::size_t>::max());
    std::bitset<maxBits> allBitsSet(std::numeric_limits<std::size_t>::max());
    //std::size_t mask((allBitsSet >> (maxBits - end)) ^(allBitsSet >> (maxBits - begin)));
    std::bitset<maxBits> mask = (allBitsSet >> (maxBits - end)) ^(allBitsSet >> (maxBits - begin));

    //std::size_t bitsetValue(value);
    std::bitset<maxBits> bitsetValue(value);

    auto maskedValue = bitsetValue & mask;
    auto result = maskedValue >> begin;

    //std::cout << static_cast<std::size_t>(result) << std::endl;
    std::cout << static_cast<std::size_t>(result.to_ulong()) << std::endl;
}

Which in fact should return the same value as value, but for some reason the version with std::bitset works just fine and version with std::size_t does not.

It is strange as such, because AFAIK std::bitset, when something is wrong simply throws exception and what is more AFAIK bitset should behave the same way as operations on unsigned integers, but as we can see even if bitset has same number of bits it does not behave the same. In fact it seems for me, that std::bitset works fine, while std::size_t does not.

My configuration is: intel corei7 - g++-5.4.0-r3

Aucun commentaire:

Enregistrer un commentaire