2

If I have -2 (11111111111111111111111111111110), is there a neat ARM instruction or a series of such that will make it (00000000000000000000000000000010). OR or XOR would not work from what I have tried since I loose the 30th bit.

Thank you

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
boinka
  • 145
  • 1
  • 11
  • 1
    ARM's negate instruction is `rsb dst, src, #0` (reverse-subtract). You can `tst` / predicated-`rsb`. I think that's what C++ compilers will do when inlining / optimizing `std::abs`, but you should try compiling an `abs` function with optimization enabled. – Peter Cordes Nov 15 '18 at 02:21
  • which arm instruction set? did you look at NEG? you do need the compare as shown in the checked answer... – old_timer Nov 15 '18 at 15:48

1 Answers1

4

For finding the absolute value of an integer, use a comparison and a subtraction.

@ input in r0
cmp r0, #0          @ is r0 < 0?
rsbmi r0, r0 #0     @ if yes, r0 = 0 - r0
fuz
  • 88,405
  • 25
  • 200
  • 352
  • `mvn` a bitwise NOT, ones-complement inversion rather than two's complement. http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0204j/Cihcdbca.html. Like I commented, you can use `rsbmi r0, #0` – Peter Cordes Nov 15 '18 at 11:36
  • @PeterCordes Clearly you are right. I though for a second that `mvn` stood for “move negated.” That said, did you get my email? – fuz Nov 15 '18 at 11:39
  • I did, thanks for the reminder. I should have some time to look at that today. – Peter Cordes Nov 15 '18 at 11:43
  • @PeterCordes I'm looking forwards to your comments! – fuz Nov 15 '18 at 11:44
  • 2
    Worth noting that if you're using an ARMv7 or ARMv8 device, you will be using the Thumb-2 instruction set which does not include conditional execution of non-branch instructions. You will need an `it mi` before the `rsbmi`. Many assemblers will insert this for you, though some will warn because you're getting an instruction you didn't explicitly request. See https://community.arm.com/processors/b/blog/posts/condition-codes-3-conditional-execution-in-thumb-2 – cooperised Nov 15 '18 at 13:44