2013-01-20 32 views
1

我必須使用java設置半字節的整數。老實說,我很困惑如何移動/設置/更改一個半字節到我想要的半字節。我的電訊管理局告訴我,它應該是大約5行代碼,但我不知道如何啓動它。任何幫助是極大的讚賞。設置半字節爲int - java

/* Examples: 
*  setNibble(0xAAA5, 0x1, 0); // => 0xAAA1 
*  setNibble(0x56B2, 0xF, 3); // => 0xF6B2 
* 
* @param num The int that will be modified. 
* @param nibble The nibble to insert into the integer. 
* @param which Selects which nibble to modify - 0 for least-significant nibble. 
*    
* @return The modified int. 
*/ 
public static int setNibble(int num, int nibble, int which) { 
     // i know I will be using bit-wise operators but do not know how to use 
     // them in this situation 
     return 0; 
} 

回答

2

首先,你需要屏蔽掉你要設置的四位(使用按位&做到這一點)。

設置半字節(轉移到想要的位置)並使用按位|來設置半字節。

由於這看起來像功課,我不會發布代碼。

+0

所以我有這樣的東西在我的方法裏面,int temp =(num >> which); \t \t temp =(temp << 4)|蠶食; \t \t return temp; –

+0

你不想改變'num',因爲這樣你會失去位。只需移動你的面具和*半字節*。 – MrSmith42

+0

謝謝,我會給它一個鏡頭,並給你反饋 –