http://codepad.org/wByY34pA
//its an improvement on my old bithack of x* ((((x >= 0) | 0) << 1) - 1)
void main(){//abs without multiply
int a=-23;// if neg +2a -a=a if pos -a + 2a=a
int b= ((-a)<<(a<0))+((a)<<(a>0));
printf("a:%d b:%d",a,b);
}
Name:
FrozenVoid!!mJCwdV5J0Xy2A212011-11-04 23:07
It works for for all types, doubles, floats, ints,chars,etc. and is not arch-specific.
>>3
>Assumes 32768u is max short value, 2147483648u max int, etc
Sure is portability.
Name:
FrozenVoid!!mJCwdV5J0Xy2A212011-11-04 23:39
Note for floating-point there is need to use *2 instead of shift.
here is floating point compatible, but slower version.
void main(){//abs for floats:1 multiply
double a=-23.2;//
double b= ((a)*((a>0)-(a<1)));
printf("a:%f b:%f",a,b);
}
>>12
i use this before in some C code
x*=(x<MAX_VALUE) // if x is less then MAX_VALUE its*1 else *0
it branchlessly caps x at MAX_value to 0(effectivelly making MAXVALUE same as INT32_MAX overflowing to 0)
Name:
FrozenVoid!!mJCwdV5J0Xy2A212011-11-05 2:30
I use this trick to find maximum branchlessly and other results.
Put 2 numbers into array
so x[0]= A and a[1]=B
maximum? x[a<b]
Minimum? x[a>b]
This can extended by removing branching and using boolean values for all code.
Name:
Anonymous2011-11-05 5:14
Can't you just check the first bit to see if it's negative?
>>15
First bit does not ==sign, its odd/even, you mean most-significant bit(x>>31 for Int32) you still have to convert that bit into sign(0 or -1 to 1:-1), and its limited to ints with 4bytes length. http://codepad.org/Q7yDw1U8 you probably mean something like this
Name:
Anonymous2011-11-05 7:52
>>16,17
Yeah you're right, I meant setting the most-significant (I trust that this is the right terminology) bit to 0 for signed integer types.
Name:
Anonymous2011-11-05 8:41
>>18
What about two's complement for negative numbers?
Name:
Anonymous2011-11-05 9:04
Fastest way to get signed that I can imagine:
Bitwise AND along with the largest possible number for that data type
e.g. signed char to unsigned value:
Maximum signed char value:
0111 1111 (127)
Arbitrary signed char value:
1010 0111 (-39)
Bitwise &:
1010 0111 & 0111 1111
0010 0111
No idea why you rape your mother though.
Name:
Anonymous2011-11-05 9:17
>>20
Binary representation of a 8-bit signed integer with the value of -39 would be 11011001.
There is a transfinite sequence of cardinal numbers:
0, 1, 2, 3, ..., n; ℵ0, ℵ0, ℵ1, ... ℵα, ...
Name:
Anonymous2013-09-01 17:16
int abs(int value) /* returns the absolute value. Does not multiply */
{
if (value < 0) {
return 0 - value;
return value;
}
Original code do not steal.
Name:
Anonymous2013-09-01 19:26
Each set in this hierarchy is assigned (by transfinite recursion) an ordinal number α, known as its rank. The rank of a pure set X is defined to be the least upper bound of all successors of ranks of members of X.