Java bit operations: replacing nibble of hex code

I need to write this code for my homework, but I don't even know where to start. Here is the javadoc for the method I should 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's what I have. I have this to work with the first example in the javadoc, but I know this is not the case 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 use shifts or not? I was told that I can do this method in one line of code. Thanks for the help in the advanced work!

0


source to share


1 answer


I suggest you:



  • extract the bits you want to keep by creating a mask and using &

  • put the bits you want to add to the position you want with left shift <<

  • combine them with bitwise OR
+5


source







All Articles