I've been looking on the 'net and I haven't found many examples of how to do the abs(x) function for signed variables in assembly efficiently, both in speed and in code space.
abs(x) can be implemented in C like this:
But translating that into assembly is the difficult part. It's also not very efficient, involving a branch and compare.
Now I have found that this code may do the job, for 8-bit PICs:
From here: http://www.piclist.com/techref/microchip/condrepl.htm
This essentially tests if the number is negative and computes its complement. It can vary from 4 cycles to 6 cycles. I'm working with dsPIC processors, but this code can be made to fit with few changes.
But I was wondering if there was a faster way. I am dealing with a speed critical application and every last bit of speed I can squeeze out would be good. If anyone knows it would be great. Thanks.
abs(x) can be implemented in C like this:
Rich (BB code):
int abs(int x) { return (x < 0) ? -x : x; }
Now I have found that this code may do the job, for 8-bit PICs:
Rich (BB code):
btfsc R0,7
decf R0
btfsc R0,7
comf R0
This essentially tests if the number is negative and computes its complement. It can vary from 4 cycles to 6 cycles. I'm working with dsPIC processors, but this code can be made to fit with few changes.
But I was wondering if there was a faster way. I am dealing with a speed critical application and every last bit of speed I can squeeze out would be good. If anyone knows it would be great. Thanks.