jueves, 8 de agosto de 2013

Arduino Variables, Signed VS Unsigned

What's the difference?

Signed/Unsigned are reserved words that specifies whether a variable can contain negative numbers, for this, uses the first bit (0 or 1) to indicate whether it is positive or negative, so it reduces the size of the variable at a half, see this:


Language      Type                       Size                              Range                 Meaning

C#                byte                         8-bit (1 byte)          0 to 255           Byte with sign
C#                sbyte                       8-bit (1 byte)          -128 to 127       Byte without sign

Arduino          Signed byte     8-bit (1 byte)         0 to 255            Byte with sign
Arduino          Unsigned byte   8-bit (1 byte)         -128 to 127       Byte without sign

Signed vars:  00000011 = 3       //     10000011 = -3

                       01111111 = 127  //      11111111 = -128

Unsigned vars: 00000011 = 3      //   10000011 = 131
                          01111111 = 127  //   11111111 = 255


Note: by default arduino uses signed variables, so it's the same using "byte my_var" than "signed byte my_var"

Tip:

When a variable exceed their maximum capacity, turns around his minimum capacity. In both directions.
Example: 

  unsigned int x;      // contains 0 to 65535
  x = 0;               // contains 0
  x = x -1;            // now contains 65535 (turning into max)
  x = x +1;            // contains 0 (returns to minimum)


Remember:

Signed: Means number can be negative (half capacity), top bit indicates the sign (1 = negative, 0 = pos.)

Unsigned: Means that number can only be positive (full capacity)

Reference:

http://arduino.cc/es/Reference/UnsignedInt
http://arduino.cc/es/Reference/Int

------------

No hay comentarios:

Publicar un comentario