Niyaz K
Niyaz K

Reputation: 13

bitset not working with some numbers

i am trying to convert 8 Byte wide number to bit strings .

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <bitset>
     void getAsString(int64_t mask )
    {
        printf("mask = %lld\n", mask);
        std::string test = std::bitset< 64 >( mask ).to_string();
        printf("test = %s \n", test.c_str() );
    }

    int main()
    {
        int64_t allowedBits[4] = { 0x0000000000000001L, 0x0000000000010000L, 0x0000000100000000L, 0x0001000000000000L };
        for (int i = 0; i < 4; ++i)
        {
            getAsString(allowedBits[i]);
        }
    }

Below is the output on Linux Machine

No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 16.04 LTS Release: 16.04 Codename: xenial g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

mask = 1
test = 0000000000000000000000000000000000000000000000000000000000000001 
mask = 65536
test = 0000000000000000000000000000000000000000000000010000000000000000 
mask = 4294967296
test = 0000000000000000000000000000000100000000000000000000000000000000 
mask = 281474976710656
test = 0000000000000001000000000000000000000000000000000000000000000000 

Same code this machine . Distributor ID: CentOS Description: CentOS release 6.8 (Final) Release: 6.8 Codename: Final

g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-17)

Give the below output

mask = 1
test = 0000000000000000000000000000000000000000000000000000000000000001
mask = 65536
test = 0000000000000000000000000000000000000000000000010000000000000000
mask = 4294967296
test = 0000000000000000000000000000000000000000000000000000000000000000
mask = 281474976710656
test = 0000000000000000000000000000000000000000000000000000000000000000

I have checked the width of the int64_t . it is 8 in both machines. For mask 4294967296 and 281474976710656 the string is zero .

Any help here would be really appreciated .

Upvotes: 1

Views: 834

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154045

Based on the version of your compiler (gcc-4.4.7) the code is probably using a library which isn't updated to deal with C++11. The pre-C++11 specification of the std::bitset<N> constructor taking an integer used unsigned long. For a 32 bit build unsigned long uses 32 bits. As a result the argument will be truncated before passed to std::bitset<N>'s constructor.

I verified that libstdc++ shipping with gcc-4.4.7 does use unsigned long as the type in the constructor.

Upvotes: 1

Related Questions