The method takes in an n-bit 2's complement number whose absolute value we're trying to find, and the number of bits that the number will be. Here are some examples:
abs(0x00001234, 16); // => 0x00001234
abs(0x00001234, 13); // => 0x00000DCC
So you can see that in the first example that 0x00001234 just yields itself because with 16 bits it has enough leading zeroes to just be itself.
However, for the second example, using 13 bits makes 0x00001234 have a 1 in the sign bit, so when you convert this 13-bit number to a positive number, it yields 0x00000DCC.
I feel like what I have so far should work, but it isn't working for some cases :/ Any idea what's wrong or what direction I should be going in?
EDIT: Also forgot to mention, we can't use >>>, or +,-,*,/ unless we're just incrementing by 1.
public static int abs(int num, int n)
{
boolean set = ((1 << n-1) & num) == (1 << n-1);
if (!set) {
return num;
} else {
int bitmask = (0x7FFFFFFF >> (32-n)) | (1 << n-1);
return (num ^ bitmask) + 1;
}
}