0

I have to write a method that takes in an integer as a parameter (0, 1, 2, or 3). I have to use that to create a bitmask with a 0. So, if the parameter is 0, than the bitmask will be FFF0, for 1: FF0F, 2: F0FF, 3: 0FFF. I am trying not to hardcode it.

What I have tried, but it only works partially:

int bob = 0xFFFF;
int multi = 2;

multi = multi << param;

this works with 1 and 2, and for even those, it makes it 0xFF00, and 0xF000.

I am trying not to use multiplication either (that would make it a lot easier, so I don't want to use it).

Jeff
  • 12,555
  • 5
  • 33
  • 60
sparkonhdfs
  • 1,313
  • 2
  • 17
  • 31
  • Removing all mentions of "java" is probably not actually that good an idea... Made me not sure how it was going to handle negative numbers (e.g. manu-fatto's answer wouldn't work if `int` means a 16 bit number - since that would make `0xFFFF` equal to -1) – Jeff Jan 23 '13 at 00:31

3 Answers3

2

I would say:

0xFFFF - (0xF << (param * 4))
Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64
2

Something like this:

bitmask = 0xFFFF;
bitmaskmask = 0xF;
bitmaskmask = bitmaskmask << parameter * 4;
bitmask = bitmask ^ bitmaskmask;
Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
Patashu
  • 21,443
  • 3
  • 45
  • 53
  • thanks. I used a similar technique to avoid multiplication, using 2 if clauses. I used an int 2 as a base and depending ont he parameter I shifted it, b/c 2 is 0b10, and 2 << 1 is 0b100, which is 4, and 2 << 2 is 0b1000, which is 8 and so on. thanks. – sparkonhdfs Jan 23 '13 at 00:37
0

Given your inputs, you can achieve what you are looking for using the bitwise XOR operation as follows:

xorMask = 0x000F << (4*multi) ;
result = bob ^ xorMask ;

This creates an XOR mask with 1 bits in the appropriate portion of the 16 bit value, then XORing it with the input to 0 those bits in the output.

John Haager
  • 2,107
  • 1
  • 17
  • 22
  • Except... if `multi == 2 && bob == 1` you wind up with `0x0F01` instead of `0x0001`. – Jeff Jan 23 '13 at 00:42