问题
I have to set the nibble for an integer using java. Honestly I am confused on how to shift/set/change a nibble to an nibble that I want. My TA told me it is supposed to be about 5 lines of code but I don't know how to even start it. Any help is greatly appreciated.
/* 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;
}
回答1:
First you need to mask out the nibble you want to set (use bitwise and &
to do this).
Than set the nibble (shifted to the wanted position) and use bitwise or |
to set the nibble.
Since this looks like homework, I will not post the code.
来源:https://stackoverflow.com/questions/14427737/setting-the-nibble-for-an-int-java