0

To be more specific, there are constraints on my assignment that disallow me to use multiplication and more than 2 if-else statements. The method should take a number, such as 0xAAA5, and replace one of the 4-bit sections with the given nibble, such as 0x1. Here is my code right now:

public static int setNibble(int num, int nibble, int which) {
    num = num & (0xFFFF - (0xF << (4 * which)));
    num = num | ( (nibble) << (4 * which) );

    return num;
}

I basically just want to left shift by which*4, but I can't figure out how to do that without multiplication, or some kind of if-else statement.

Perception
  • 79,279
  • 19
  • 185
  • 195
Evan LaHurd
  • 977
  • 2
  • 14
  • 27

1 Answers1

2

4 * which == which << 2, so you can use that.

fge
  • 119,121
  • 33
  • 254
  • 329