0

Does numeric operations for (1) two signed integers and (2) for two unsigned integers result in different assembly code? Assume integer width are the same, say, 64-bits.

By "numeric operations" I mean operations like +, -, *, /, % (especially the last two). My guess of the answer is "they are the same" judging from the x86 assembly reference and the impression that signedness is how computer display a given bit pattern to screen, but I'd like to verify this claim. It might seem a silly question..

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Leedehai
  • 3,660
  • 3
  • 21
  • 44
  • On any 2's complement architecture, no (except for multiply and arithmetic vs. logical right shift). – Peter Cordes Aug 13 '18 at 09:08
  • 1
    [Difference between signed and unsigned on bitwise operations](https://stackoverflow.com/q/13224273/995714) – phuclv Aug 13 '18 at 09:09
  • 1
    it depends on how the signed values are encoded, on x86 the two's complement is used, so `add` and `sub` are bit-wise sign-neutral and don't care. For multiplication and division there are unsigned/signed variants of instructions (`mul` vs `imul` and `div` vs `idiv`), but if you fully understand how the signed values are encoded, in certain special cases (limited inputs or limited output usage) you can use the other one (like `imul` even for unsigned values, if you are interested only in low-bit part of results, etc). – Ped7g Aug 13 '18 at 09:09
  • @Ped7g ouch my bad.. I suggest you convert your comment to an answer. – Leedehai Aug 13 '18 at 09:11
  • @Ped7g but [this answer](https://stackoverflow.com/a/13229313/8385554) lists multiplication as one of the case where signedness is irrelevant? – Leedehai Aug 13 '18 at 09:36
  • @Leedehai only when truncated to 64 bit (low part of result). Then the negative values will basically always overflow, and the low 64b part will be "correct" in terms of truncation. That answer which claims multiplication to be the same, is also assuming the "our behaviour on overflow is wraparound modulo 2n", so then it is true. But both `imul/mul` allows you to extract extended 128 bit result, where the signedness matters. – Ped7g Aug 13 '18 at 09:41

0 Answers0