Reputation: 143
If I wanted to find the absolute value of a 24-bit two's complement integer, would it be best to mask the integer, and if needed negate the original number?
To better illustrate what I mean:
public static int bitwiseAbsoluteValue(int n) {
if (n == 0x800000) {
return 0x000000;
} else {
if ((n & 0x800000) == 0x800000) {
return (~n + 1) & 0x7FFFFF;
} else {
return n;
}
}
}
Would this work?
Upvotes: 1
Views: 3333
Reputation: 311039
Shift it left 8 bits then shift right 8 bits again (arithmetic shift, not logical shift). That will propagate the sign bit correctlyif there is one.
Upvotes: 0
Reputation: 734
That would work. Though you can only store up to +127, and down to negative -128. So the negation of -128, plus 1 would be a negative number. There's not much that can be done about that if the returned number is also supposed to be 24-bits.
Sorry, replace the +127 and -128 with the largest positive and negative numbers that can be stored with 24-bits. They're meant to illustrate the point that in 2's complement you can store negative number that has an absolute value 1 larger than the biggest positive number you can store. So you need to figure out how you want to deal with it if the number you're given is the biggest negative number (0x80000000 in 2's complement).
Upvotes: 0
Reputation: 20664
You could just subtract it from 0x1000000 (which is 1<<24) if bit 23 is set.
Upvotes: 0
Reputation: 2616
Well, one way it can be done without Math.abs(n)
would be something like this:
public static int findAbs(int n){
if(n<0){return -1*n;}
return n;
}
Upvotes: 0
Reputation: 32596
You'd also need to mask the first return value:
return (~num + 1) & 0x7FFFFF;
And you'd need to work out what you want to do if the the value passed in is 0x800000
. The current function would return 0
, which is obviously not correct.
Upvotes: 2