Solved

# Bitwise Copy

Posted on 2000-05-15
218 Views
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.

regards
mak
0
Question by:makrand
• 2
• 2

LVL 16

Accepted Solution

ID: 2811699
There should be no special handling required:

int i=0xffffffff;
long l=i;

Since l is a "wider" type than i, it can be assigned without any trouble at all.
0

Author Comment

ID: 2811903
When u check the binary value of it using
Long.toBinaryString(longVal) and
Integer.toBinaryString(intVal), you will notice the diffrence
0

LVL 16

Expert Comment

ID: 2812385
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.
0

Author Comment

ID: 2818431
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;

}
0

## Featured Post

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.