Here is the code:
#include <iostream>
using namespace std;
template<class T>
void printbinary3(T num){
for(int i = sizeof(T) * 8 - 1; i >= 0 ; --i) {
if((1 << i) & num)
cout << "1";
else
cout << "0";
}
cout << endl;
}
int main ()
{
char a = 1;
short b = 1;
int c = 1;
long d = 1;
__int64 e = 1;
unsigned __int64 f = 1;
printbinary3(a);
printbinary3(b);
printbinary3(c);
printbinary3(d);
printbinary3(e);
printbinary3(f);
return 0;
}
Here is the output:
00000001 0000000000000001 00000000000000000000000000000001 00000000000000000000000000000001 0000000000000000000000000000000100000000000000000000000000000001
When compiling I get this error for the unsigned __int64 variable – f.
1> : warning C4334: '<<' : result of 32-bit shift implicitly converted to
64 bits (was 64-bit shift intended?)
1> xx.cpp(66) : see reference to function template instantiation
'void printbinary3<unsigned __int64>(T)' being compiled
Why am I not seeing
0000000000000000000000000000000000000000000000000000000000000001
as the output for the 64 bit integer?
Angus
In your
printbinary3function:Here, you are creating a literal
1of typeint, which most probably is 32 bit. IfT = __int64, you will shift it for too many bits, leading to an overflow and the warning.Instead of using implicit
int, explicitely create aTinstead:This should fix the warning and the output.