Monday, 2 September 2013

set 4-bit nibble in an int type

set 4-bit nibble in an int type

we need to come up a method that set a 4-bit nibbles in an int output
should like this:
setNibble(0xAAA5, 0x1, 0); // => 0xAAA1
setNibble(0x56B2, 0xF, 3); // => 0xF6B2
This is what i wrote...
public static int setNibble(int num, int n, int which)
{
int output;
if(which ==0)
{
output = (num & 65280) |nibble;
}
else
{
int shift = nibble << 8 ;
output = (num & 255) | shift;
}
return output;
}
but there have something wrong that I cannot figure out
setNibble(FFFF, 0, 0): Expected: FFF0 Result: FF00
setNibble(FFFF, 6, 1): Expected: FF6F Result: 6FF
setNibble(1312, E, 1): Expected: 13E2 Result: E12
Anyone can help me ? Thanks in advance!

No comments:

Post a Comment