James Carter
James Carter

Reputation: 387

simple bit operation for int to short

Having trouble writing the bit operations to convert an int to a short depending on which 16 bits wanted, ex: 1 will be the left most 16 bits and 0 will be the right most 16. All help is appreciated!

    /**
 * Get a short from an int.
 * 
 * Examples: 
 *     getShort(0x56781234, 0); // => 0x1234
 *     getShort(0xFF254545, 1); // => 0xFF25
 * 
 * @param num The int to get a short from.
 * @param which Determines which short gets returned - 0 for least-significant short.
 *            
 * @return A short corresponding to the "which" parameter from num.
 */
public static int getShort(int num, int which)
{

    if(which == 1){
        return num>>16;
    }
    else{
        return num << 16;
    }
    }

I do not want to use >>> or <<<

Upvotes: 0

Views: 338

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

This snippet will work correctly with both positive and negative numbers:

public static int getShort(int num, int which) {
    if(which == 1){
        return num >>> 16; // Use >>> to avoid sign-extending the result
    } else{
        return num & 0xFFFF;
    }
}

Upvotes: 1

NPE
NPE

Reputation: 500367

The

    return num << 16;

should read

    return num & 0xFFFF;

Also,

    return num >> 16;

should read

    return num >>> 16;

Upvotes: 1

Related Questions