I had to admit, that exercise mad me think.. although i didn't get the correct answer! but still, its one of those 'rust-busters' you tend to like! thanks for the trivia/puzzle chris!
Lets setup the point system! also.. prizes anyone? any local sponsors?
I didn't use Math.Abs since I think it uses conditionals, just like Array.Sort. Anyone ILDASM'ed this?UPDATE: Here's the relevant decompiled code, from .NET Reflector:public static int Abs(int value){ if (value >= 0) { return value; } return Math.AbsHelper(value);}private static int AbsHelper(int value){ if (value >= 0) { return value; } if (value == -2147483648) { throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); } return -value;}Mapapaaway ba ako dito? Just in the interest of correctness.
punzie wrote:I didn't use Math.Abs since I think it uses conditionals, just like Array.Sort. Anyone ILDASM'ed this?UPDATE: Here's the relevant decompiled code, from .NET Reflector:public static int Abs(int value){ if (value >= 0) { return value; } return Math.AbsHelper(value);}private static int AbsHelper(int value){ if (value >= 0) { return value; } if (value == -2147483648) { throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); } return -value;}Mapapaaway ba ako dito? Just in the interest of correctness.
hehehe i was supposed to post this! heheh! nice one punzie!
keithrull wrote:hehehe i was supposed to post this! heheh! nice one punzie!
cvega wrote:I didn't use Math.Abs since I think it uses conditionals, just like Array.Sort. Anyone ILDASM'ed this?UPDATE: Here's the relevant decompiled code, from .NET Reflector:public static int Abs(int value){ if (value >= 0) { return value; } return Math.AbsHelper(value);}private static int AbsHelper(int value){ if (value >= 0) { return value; } if (value == -2147483648) { throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); } return -value;}Mapapaaway ba ako dito? Just in the interest of correctness.
That's nice one punzie, mine is identical to your approach:int abs(int v) { int sbit = v >> 31; return (v ^ sbit) - sbit;}And below is from the book "Bits and Bytes":int abs(int v) { return v * sign(v);}int sign(int v){ // I was thinking why the author of the book uses // v ^ ~v when it always returns -1, and then // multiply it back again to -1? // // return -1 * ( ( v ^ ~v ) - ( ( v >> 31 ) * 2) ); // So I revised it, it's much simplier this way: return 1 + ( ( v >> 31 ) * 2 );}-chris