Daniel Eugen
Daniel Eugen

Reputation: 2780

Differentiate between negative and positive numbers?

In binary we can have a signed and unsigned numbers, so let's say we are given a value of 0101 how could we tell whether it is equal to 5 or to -1 as you may notice the second bit from the left is on

Upvotes: 1

Views: 1343

Answers (2)

frasnian
frasnian

Reputation: 2003

There is no difference in binary. The difference is in how a given language / compiler / environment / processor treats a given sequence of binary digits. For example, in the Intel x86/x64 world you have the MUL and IMUL instructions for multiplication. The IMUL instruction performs signed multiplication (i.e. treats the operand bits as a signed value). There are also other instructions that distinguish between signed/unsigned operands (e.g. DIV/IDIV, MOVSX, etc.).

Here's a quick example:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main(void)
{
    int16_t  c16;
    uint16_t u16;

    __asm {
      mov al, 0x01
      mov bl, 0x8F
      mul bl          // ax = 0x01 * 0x8F
      mov u16, ax

      mov al, 0x01
      mov bl, 0x8F
      imul bl         // ax = 0x01 * 0x8F
      mov c16, ax
    };

    char uBits[65];
    char cBits[65];

    printf("%u:\t%s\n", u16, _itoa(u16, uBits, 2));
    printf("%d:\t%s\n", c16, _itoa(c16, cBits, 2));

  return 0;
}

Output is:

143:    10001111
-113:   11111111111111111111111110001111

On edit:
Just to expand on the example - in C/C++ (as with other languages that distinguish between signed and unsigned quantities), the compiler knows whether it is operating on signed or unsigned values and generates the appropriate instructions. In the above example, the compiler also knows it must correctly sign-extend the variable c16 when calling _itoa() because it promotes it to an int (in C/C++, int is signed by default - it is equivalent to saying signed int). The variable u16 is promoted to an unsigned int in the call to _itoa(), so no sign-extension occurs (because there is obviously no such thing as a sign bit in an unsigned value).

Upvotes: 1

Eudis Duran
Eudis Duran

Reputation: 782

On actual hardware the implementation of negative numbers is dependent on what the designers chose. Usually signed numbers are represented in Two's Complement

But there are Many More

Upvotes: 0

Related Questions