3

I am stuck on how to replace a 4-bit value to a certain position of an original 32-bit integer. All help is greatly appreciated!

/**
 * Set 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 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)
{
           int shifted = (nibble << (which<<2));
       int temp = (num & shifted);
           //this is the part I am stuck on, how can  I replace the original
           // which location with the nibble that I want? Thank you!
       return temp;
}
Boann
  • 48,794
  • 16
  • 117
  • 146
James Carter
  • 387
  • 2
  • 6
  • 18
  • 2
    A 32-bit `int` contains **four** bytes (8 nibbles), not eight bytes, as the comment in your code says. – Jesper Jan 21 '13 at 21:00
  • 1
    http://stackoverflow.com/questions/12302794/java-bit-operations-replacing-nibble-of-hex?rq=1 – Gothmog Jan 21 '13 at 21:01
  • Same question you asked before http://stackoverflow.com/questions/14427737/setting-the-nibble-for-an-int-java – MrSmith42 Jan 21 '13 at 21:03

2 Answers2

2
public static int setNibble(int num, int nibble, int which) {
    return num & ~(0xF << (which * 4)) | (nibble << (which * 4));
}

Here:

  • the & ~(0xF << (which * 4)) masks out the original value of the nibble;
  • the | (nibble << (which * 4)) sets it to the new value.
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0
nibble &= 0xF; // Make sure
which &= 0x3;
int shifts = 4 * which; // 4 bits
num &= ~(0xF << shifts);
num |= nibble << shifts;
return num;
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138