C++ unix 32bit to Red Hat Linux running on an x86_64 chip (64-bit server) -
i working on project porting application in c++ 32 bit unix red hat linux running on x86_64 chip (64-bit server). facing issues related long data types.i wrote sample program print binary long , unsigned long value of 1. has 1 in middle:
ul = 0000000000000000000000000000000100000000000000000000000000000001
l = 0000000000000000000000000000000100000000000000000000000000000001
string binary(unsigned long i) { int n = sizeof(unsigned long); string s; n *= 8; --n; while (n >= 0) { unsigned long mask = (1 << n); s += (mask & ? "1" : "0"); --n; } return s; } string binary(long i) { int n = sizeof( long); string s; n *= 8; --n; while (n >= 0) { long mask = (1 << n); s += (mask & ? "1" : "0"); --n; } return s; } int main() { unsigned long ul = 1; long l = 1; cout << "sizeof ul = " << sizeof ul << ", ul = " <<ul<< endl; cout << "sizeof l = " << sizeof l << ", l = " << l << endl; cout << "ul = " << binary(ul) << endl; cout << "l = " << binary(l) << endl; return 0; }
as can see not getting why there 1 in middle. causing run time issues in application. please let me know. getting 1 middle in red hat linux running on x86_64 chip (64-bit server) not in unix , cause of run time issues. idea please let me know.
the problem here:
unsigned long mask = (1 << n);
apparently, unsigned long
has 8 byte , normal int
has 4 byte on system.
here have int
value 1 (every literal value int
if nothing else explicitely specified). you´re doing shifting on 4 byte int
, , then result converted 8 byte save in mask
. shifting more 31 bit in 4 byte, yet you´re doing until 63 bit.
to solve problem, have tell compiler 1
meant 8 byte unsigned long
.
3 possibilites:
unsigned long mask = (1ul << n); //or unsigned long mask = ((unsigned long)1 << n); //or unsigned long mask = 1; mask = mask << n;
the other function (for signed type) has same problem.
first variant, use l
there, without u
.
Comments
Post a Comment