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.
The literal 1 defaults to an integer. Cast it to long long to solve the problem.
std::cout<<(bool)(number&(((long long)1)<<i));
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With