Link to home
Start Free TrialLog in
Avatar of makrand
makrand

asked on

Bitwise Copy

Hi,
I have an int i=0xffffffff which I want to copy to a long l , so that the result is l=0x00000000ffffffff; , Can you pls tell me how to do it.

thanks in advance
regards
mak
ASKER CERTIFIED SOLUTION
Avatar of imladris
imladris
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of makrand
makrand

ASKER

When u check the binary value of it using
Long.toBinaryString(longVal) and
Integer.toBinaryString(intVal), you will notice the diffrence
Yes, you are quite right. I apologize. The reason for the behaviour you see is that integers (and longs) are signed quantites. The value 0xffffffff represents -1 in an integer. When it is converted to a long, the sign bit is extended leftward (i.e. if the topmost bit is 0 the top 4 bytes of the long are set to 0, but if the top bit is 1 the top 4 bytes of the long are set to 1). Thus the long becomes 0xffffffffffffffff which also represents -1.

To force the long to contain 0xffffffff you will need to mask the top 4 bytes to 0:

long l=i&0xffffffffL;

Make sure you add the L to the constant which will cause the constant to be long (i.e. 8 bytes). This will cause the variable i to be widened (and sign extended) (in order to do the bitwise operation), then top 4 bytes will by masked off.

Without the trailing L, the bitwise operation would occur first (having no effect) and then the result would be widened (leaving you with the sign extension again.
Avatar of makrand

ASKER

Thanks very much, I was not getting the exact way to do a bitwise operation, I was doing something like this

private static long getBinaryLongValue(int val)
{
String s = Integer.toBinaryString(val);
long l = Long.parseLong(s,2);
return l;  
             
}