Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing bits in long long number (C++)

I want to print all bits of a long long number. When I am doing it in main() everything is fine, but in printBits() function (where code is same) there is an extra 1 on 32th bit.

The code:

#include <iostream>

void printBits(long long number)
{
    std::cout<<number<<" -> ";
    for (char i=63; i>=0; --i)
    {
        std::cout<<(bool)(number&(1<<i));
    }
    std::cout<<std::endl;
}

int main()
{
    long long number=1;

    std::cout<<number<<" -> ";
    for (char i=63; i>=0; --i)
    {
        std::cout<<(bool)(number&(1<<i));
    }
    std::cout<<std::endl;

    printBits(number);

    return 0;
}

Result is:

1 -> 0000000000000000000000000000000000000000000000000000000000000001
1 -> 0000000000000000000000000000000100000000000000000000000000000001

Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.
like image 375
Rafał Majewski Avatar asked May 01 '18 20:05

Rafał Majewski


2 Answers

The literal 1 defaults to an integer. Cast it to long long to solve the problem.

std::cout<<(bool)(number&(((long long)1)<<i));
like image 80
Cpp plus 1 Avatar answered Oct 04 '22 17:10

Cpp plus 1


As Cpp plus 1's answer shows you need to modify the (default int) literal 1 to a long long literal 1LL or 1ll.

However, you might be better off using std::bitset instead of your function:

#include <bitset>
long long number = 1;  // int number = 1;  also works
std::bitset<64> bits(number);
std::cout << number << " -> " << bits << std::endl;

yields:

1 -> 0000000000000000000000000000000000000000000000000000000000000001

The reason you are getting this output is because for the specific hardware/compiler you are using:

a << x operation works in the following way: a << (x mod (8 * sizeof(a)). Therefore for 1 you get 1 << (x mod 32). This means that on the 32nd loop iteration:

std::cout << (bool)(number & (1 << 32));
// becomes
std::cout << (bool)(number & (1 << 0));
// printing '1'
like image 36
Kostas Avatar answered Oct 04 '22 18:10

Kostas