2013-01-21 35 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