Mike36

I'm trying to decide how to structure my code based on Math.Abs function. Does it just flip the signed bit to make the number positive Or does it check for a negative value and if found, multiply the number by -1

### Re: XNA Framework Math.Abs inner workings?

waruwaru

Ummm.. If it matters to you that much, why don't you just write your own :) I mean you can't change the function in the Math lib even if you found out. Best thing would be for you to profile your code and find which routine have the best performance.

### Re: XNA Framework Math.Abs inner workings?

Mike36

I suppose it doesn't matter that much, but was interesting question anyway.

### Re: XNA Framework Math.Abs inner workings?

Fluxtah

It does more or less exactly what you said it does, if the number is greater than zero the number is returned, if not its negated/

### Re: XNA Framework Math.Abs inner workings?

BrianOsman

Yes. Just to point out, though - implementing your own version of things like this is a bad idea. Computers (in general) do not use signed-magnitude representation of integers, they use 2s complement. Thus, flipping the sign bit doesn't actually produce a value with the same magnitude. Of course, you could be operating on a platform where that does work. The only way to ensure that your code works everywhere is to use operations that don't depend on the bit-representation of numbers. Either things like multiplying by -1 or (even better), just calling Math.Abs. ### Re: XNA Framework Math.Abs inner workings?

Johnnylightbulb

This is implemented in MSCorlib -> Reflector says it checks the sign and if needed returns -value. This means the CLR compiles -value into most likely an ASM for exactly that.

### Re: XNA Framework Math.Abs inner workings?

Mike36

I actually came up with a different solution to my problem. Basically, I wanted to either rotate left or rotate right by a specified amount (say, 90 degrees). In my code, I added an increment to the current angle to track when I've rotated enough, then used a Quaternion.CreateFromAxisAngle to do the rotating. If I wanted to turn the opposite way, I originally had a negative angle. Hence the need to use Math.Abs in my code. Then I got smart and instead of, say using Vector3.Forward as my axis all the time, I used Vector3.Forward to rotate one way, and Vector3.Backward to rotate the other way. That did the trick and I didn't have messy code as a result.