Thursday, August 19, 2010

Sign Extension in Java

Sign extension is a rule in Java by which widening conversion is carried out. While we are on the mood to know something, Let us see the whole process by an Example.

Consider the expression: "byte b=0xf0;". It is storing f0(hex) = 240(decimal) = 11110000(binary) in variable b. Thus the bits stored in b will be "11110000".

Now we perform "b=(byte)(b>>>4);" At first glance it looks like shifting "11110000" four times right with 0's filled in MSB, result is going to be "00001111". But its not..!! Lets see where does it have a catch. Following steps will occur in order,


1) Widening Conversion:

Widening conversion is done when byte is converted to integer, integer to long and so on. But there is a catch when we handle Widening conversion with negative numbers

For any operation performed, first the operators are brought to same level - minimum integer level is required. hence when when we try to shift 'b' in byte, it is first converted to integer. This process of conversion of smaller width variable to larger width variable(E.G. byte to integer) is called Widening conversion.

Widening conversion follows the rules called "Sign Extension". It states that "On doing widening conversion, fill the leading bits with MSB". Thus if you are widening negative number, fill the first 24 bits with 1 and with 0 if you are widening positive number.



2) Shift Operation:

    After 'b' is widened to integer, All the bits are shifted to right. Zeros are filled from left as it is Fill-Zero-Right-shift operation. "b=(byte)(b>>>4);" Simple as cake.



3) Truncation Operation:

    As the name suggests this operation will simply cut-off first 24-bits and store last 8 bits in 'b'.


Thus the final result computes to b="11111111".

This will suffice for today... And in case of queries, please drop a reply.

2 comments:

  1. nice information shared by you but has an unexpected end .... its better if you could have extended it a bit more ...

    ReplyDelete
  2. @Shailiesh: Thank you for your valuable comment. Can you please elaborate what more you expecting at the end.

    ReplyDelete