Question

How to get long value of an int? For example how to get long value of -127?

Was it helpful?

Solution

If you are talking about bit representation for negative numbers having a leading 1, then you could use:

int intValue = -127;
long longValue;
if((0x80 << (sizeof(int)-1)) & intValue)
{
    longValue = (0x80 << ((sizeof(long)-1)*8)) | ((0x80 << ((sizeof(int)-1)*8)) ^ intValue);
}else{
    longValue = intValue
}

I hope I did not mess up with the brackets.

OTHER TIPS

int foo = -127;
long bar = foo;
assert(bar == foo); // We simply state that the values are the same

Or:

// Decent compilers will optimize this away in release build.
long long_from_int(int x) { return x; }

int foo = -127;
assert(long_from_int(foo) == -127L);

That's it. Life doesn't get any easier than that :)

Use: Long.valueOf(int)

Or if you have an 'Integer' you can also do:

Integer x = - 127; long y = x.longValue();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top