Setting the nibble for an int - java [duplicate]

好久不见. 提交于 2019-12-24 12:52:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!