2013-01-21 25 views
0

无法写入位操作来根据所需的16位将int转换为short,例如:1将是最左边的16位,0将是最右边的16.所有帮助表示赞赏!int的简单位操作short

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

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

回答

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; 
    } 
} 
+0

>>>是什么意思?有没有一种方法可以将其呈现在“>>”中? –

+1

@JamesCarter是的,你可以使用'(num >> 16)&0xFFFF',但是'>>>'更短,它的目的是处理你的情况。常规的>> >>符号扩展了负数,这意味着当你右移一个负数时,它的最高有效位被复制到高16位;结果'int'将为负数。当你使用>>>时,零从左边移开。 – dasblinkenlight

+0

太棒了,很有道理!在一个不同的地方工作,我处理价值的绝对值。可能会使用相同的情况 –

1

return num << 16; 

应该读

return num & 0xFFFF; 

此外,

return num >> 16; 

应该读

return num >>> 16; 
+0

怎么样'NUM >> 16'? –

+0

这并不奏效,请介绍一下你正在尝试做什么? –

+0

也可能你想'公共静态短int' – user59169