2

Is there any difference between signed and unsigned variables on bitwise operations?
For example,when dealing with unsigned numbers:
AND 00000111, 00001101
will result 00000101.

But what would happen when dealing with signed numbers?

Lior
  • 5,841
  • 9
  • 32
  • 46
  • 2
    [Which arithmetic operations are the same on unsigned and two's complement signed numbers?](http://stackoverflow.com/q/21475286/995714) – phuclv Dec 24 '16 at 11:29

2 Answers2

13

Assuming 2's complement is used for signed numbers, operations that care about signedness (ie they are different for the signed and unsigned interpretation of a bitstring) are:

  • division
  • modulo
  • right shift
  • comparisons (except equality)
  • double-width multiplication (rare outside of assembly)

Operations for which signedness is irrelevant are:

  • addition
  • subtraction
  • negation (-x means ~x + 1)
  • bitwise and
  • bitwise or
  • bitwise xor
  • bitwise not (~x means -x - 1)
  • left shift
  • multiplication
  • comparison (equality only)
harold
  • 61,398
  • 6
  • 86
  • 164
  • 1
    Can you show an example of the difference with the right shift operator between signed and unsigned? – Lior Nov 05 '12 at 15:14
  • 1
    @user1718294 signed right shifts preserve the sign, unsigned right shifts puts zeroes in the top bits. So `-1 >> 1 = -1` (signed) and `0xFFFFU >> 1 = 0x7FFF` (unsigned). – harold Nov 05 '12 at 15:26
  • Wouldn't a signed left shift preserve the sign bit as well? – Olivier Jacot-Descombes Aug 09 '17 at 19:47
  • @OlivierJacot-Descombes well you could define it that way, but I don't immediately see any uses - forcefully keeping the sign fixed in a left shift only makes any difference when the result would overflow, and that result is then not very useful. Wrapping modulo a power of two at least has some meaning. – harold Aug 09 '17 at 19:52
  • Also, doing anything else breaks the identities `x << 1 == x + x` and `x << 1 == x * 2`, which are probably too important to break. – harold Aug 09 '17 at 20:01
  • `-x` normally just means `0 - x`, not actually `~x + 1`. e.g. x86's `neg` sets flags based on `0 - x`, not `~x + 1`. – Peter Cordes Mar 26 '19 at 05:07
1

Unsigned and signed numbers are an interpretation of a bitstring. The AND operator doesn't have that notion and works on the single bits. The result will be the same in any way.

Femaref
  • 60,705
  • 7
  • 138
  • 176