Tony Stark Tony Stark - 1 year ago 98
Java Question

masking sign extension using right shift operator >>

I'm currently learning bitwise operator and have encountered the following example in the book "Java the complete reference the ninth edition".

I understand what right shift operator >> does, but I'm not exactly sure how this example actually works (maybe I don't understand how >> works after all). Could someone please kindly explain it to me?

Sometimes it is not desirable to sign-extend values when you are
shifting them to the right. For example, the following program
converts a byte value to its hexadecimal string representation. Notice
that the shifted value is masked by ANDing it with 0x0f to discard any
sign-extended bits so that the value can be used as an index into the
array of hexadecimal characters.

// Masking sign extension.

class HexByte {

static public void main(String args[]) {
char hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
byte b = (byte) 0xf1;
System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);

Answer Source

Signed left shift by 4 keeps the sign of the original number.

However ((byte)0xf1) >> 4 is -1 which isn't what you want.

You just want the lower 4 bits which is where the & 0x0f gives you just the lower 4 bits. This gives you 0xf which is the top 4 bits or 15.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download