0

根据需要的 16 位,编写将 int 转换为 short 的位操作时遇到问题,例如:1 将是最左边的 16 位,0 将是最右边的 16 位。感谢所有帮助!

    /**
 * 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;
    }
    }

我不想使用 >>> 或 <<<

4

2 回答 2

1

    return num << 16;

应该读

    return num & 0xFFFF;

还,

    return num >> 16;

应该读

    return num >>> 16;
于 2013-01-21T23:11:46.167 回答
1

此代码段适用于正数和负数:

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;
    }
}
于 2013-01-21T23:13:28.523 回答