Printing bits in long long number (C++)

  • A+
Category:Languages

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)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: