Java Bit Operations: replacing nibble of hex [duplicate]

谁说胖子不能爱 提交于 2020-01-06 08:10:34

问题


I have to write this code for a homework assignment but I don't even know where to start. Here is the javadoc to the method I have to write.

/**
* Sets a 4-bit nibble in an int

* Ints are made of eight bytes, numbered like so: 7777 6666 5555 4444 3333 2222 1111 0000
*
* For a graphical representation of this:
*   1 1 1 1 1 1                 
*   5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |Nibble3|Nibble2|Nibble1|Nibble0|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 
* Examples:
*      setNibble(0xAAA5, 0x1, 0) //=> 0xAAA1
*      setNibble(0x56B2, 0xF, 3) //=> 0xF6B2
* 
* @param num int that will be modified
* @param nibble nibble to insert into the integer
* @param which determines which nibble gets modified - 0 for least significant nibble
*            
* @return the modified int
*/

Here is what I have. I've got it to work with the first example in the javadoc, But I know this does not hold true for all cases. Especially when int which != 0;

public static int setNibble(int num, int nibble, int which)
    {
    int newNibble = (num >> 4);
    newNibble = (newNibble << 4) | nibble;
    return newNibble;
    }

Should I be using shifts or not? I was told I could do this method in one line of code. Thanks for the help in advanced!


回答1:


I suggest you;

  • extract the bits you want to keep by constructing a mask and using &
  • place the bits to want to add into the right position with left shift <<
  • combine them with bitwise OR


来源:https://stackoverflow.com/questions/12302794/java-bit-operations-replacing-nibble-of-hex

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