operaciones con números binarios

23
Operaciones con números binarios Suma de números Binarios Las posibles combinaciones al sumar dos bits son 0 + 0 = 0 0 + 1 = 1 1 + 0 = 1 1 + 1 = 10 100110101 + 11010101 ——————————— 1000001010 Operamos como en el sistema decimal: comenzamos a sumar desde la derecha, en nuestro ejemplo, 1 + 1 = 10, entonces escribimos 0 en la fila del resultado y llevamos 1 (este "1" se llama arrastre). A continuación se suma el acarreo a la siguiente columna: 1 + 0 + 0 = 1, y seguimos hasta terminar todas la columnas (exactamente como en decimal). Resta de números binarios El algoritmo de la resta en binario es el mismo que en el sistema decimal. Pero conviene repasar la operación de restar en decimal para comprender la operación binaria, que es más sencilla. Los términos que intervienen en la resta se llaman minuendo, sustraendo y diferencia. Las restas básicas 0-0, 1-0 y 1-1 son evidentes: 0 - 0 = 0

Upload: jenny-lilien

Post on 11-Nov-2014

26 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Operaciones con números binarios

Operaciones con números binarios

Suma de números Binarios

Las posibles combinaciones al sumar dos bits son

0 + 0 = 0 0 + 1 = 1 1 + 0 = 1 1 + 1 = 10

100110101 + 11010101 ——————————— 1000001010

Operamos como en el sistema decimal: comenzamos a sumar desde la derecha, en nuestro ejemplo, 1 + 1 = 10, entonces escribimos 0 en la fila del resultado y llevamos 1 (este "1" se llama  arrastre). A continuación se suma el acarreo a la siguiente columna: 1 + 0 + 0 = 1, y seguimos hasta terminar todas la columnas (exactamente como en decimal).

 

Resta de números binarios

El algoritmo de la resta en binario es el mismo que en el sistema decimal. Pero conviene repasar la operación de restar en decimal para comprender la operación binaria, que es más sencilla. Los términos que intervienen en la resta se llaman minuendo, sustraendo y diferencia.

Las restas básicas 0-0, 1-0 y 1-1 son evidentes:

0 - 0 = 0 1 - 0 = 1 1 - 1 = 0 0 - 1 = no cabe o se pide prestado al proximo.

La resta 0 - 1 se resuelve, igual que en el sistema decimal, tomando una unidad prestada de la posición siguiente: 10 - 1 = 1 y me llevo 1, lo que equivale a decir en decimal, 2 - 1 = 1. Esa unidad prestada debe devolverse, sumándola, a la posición siguiente. Veamos algunos ejemplos:

Restamos 17 - 10 = 7 (2=345) Restamos 217 - 171 = 46 (3=690)

Page 2: Operaciones con números binarios

10001 11011001 -01010 -10101011 —————— ————————— 01111 00101110

A pesar de lo sencillo que es el procedimiento, es fácil confundirse. Tenemos interiorizado el sistema decimal y hemos aprendido a restar mecánicamente, sin detenernos a pensar en el significado del arrastre. Para simplificar las restas y reducir la posibilidad de cometer errores hay varias soluciones:

Dividir los números largos en grupos. En el siguiente ejemplo, vemos cómo se divide una resta larga en tres restas cortas:

100110011101 1001 1001 1101 -010101110010 -0101 -0111 -0010 ————————————— = ————— ————— ————— 010000101011 0100 0010 1011

Utilizando el complemento a dos. La resta de dos números binarios puede obtenerse sumando al minuendo el complemento a dos del sustraendo. Veamos algunos ejemplos. Hagamos la siguiente resta, 91 - 46 = 45, en binario:

1011011 1011011 -0101110 C2 de 46 = 1010010 +1010010 ———————— ———————— 0101101 10101101

En el resultado nos sobra un bit, que se desborda por la izquierda. Pero, como el número resultante no puede ser más largo que el minuendo, el bit sobrante se desprecia.

Un último ejemplo: vamos a restar 219 - 23 = 196, directamente y utilizando el complemento a dos:

11011011 11011011 -00010111 C2 de 23 = 11101001 +11101001 ————————— ————————— 11000100 111000100

Y, despreciando el bit que se desborda por la izquierda, llegamos al resultado correcto: 11000100 en binario, 196 en decimal.

Page 3: Operaciones con números binarios

Utilizando el complemento a 1. La resta de dos números binarios puede obtenerse sumando al minuendo el complemento a uno del sustraendo y a su vez sumarle el bit de overflow (bit que se desborda).

 

Producto de números binarios

El algoritmo del producto en binario es igual que en números decimales; aunque se lleva cabo con más sencillez, ya que el 0 multiplicado por cualquier número da 0, y el 1 es elelemento neutro del producto.

Por ejemplo, multipliquemos 10110 por 1001:

10110 1001 ————————— 10110 00000 00000 10110 ————————— 11000110

En sistemas electrónicos, donde se suelen utilizar números mayores, no se utiliza este método sino otro llamado algoritmo de Booth.

 

División de números binarios

La división en binario es similar a la decimal, la única diferencia es que a la hora de hacer las restas, dentro de la división, estas deben ser realizadas en binario. Por ejemplo, vamos a dividir 100010010 (274) entre 1101 (13):

100010010 |1101 ——————- 0000 010101——————— 10001- 1101——————— 01000 - 0000 ——————— 10000 - 1101 ——————— 00111

Page 4: Operaciones con números binarios

- 0000 ——————— 01110 - 1101 ——————— 00001

 

Conversión entre binarios y decimales, binario a octal y de binario a hexadecimal

Binario a decimal

Para realizar la conversión de binario a decimal, realice lo siguiente:

1. Inicie por el lado derecho del número en binario, cada número multiplíquelo por 2 y elévelo a la potencia consecutiva (comenzando por la potencia 0).

2. Después de realizar cada una de las multiplicaciones, sume todas y el número resultante será el equivalente al sistema decimal.

Ejemplos:

110101 (binario) = 53 (decimal). Proceso:

1*(2) elevado a (0)=10*(2) elevado a (1)=01*(2) elevado a (2)=40*(2) elevado a (3)=01*(2) elevado a (4)=161*(2) elevado a (5)=32La suma es: 53

10010111 (binario) = 151 (decimal). Proceso:

1*(2) elevado a (0)=11*(2) elevado a (1)=21*(2) elevado a (2)=40*(2) elevado a (3)=01*(2) elevado a (4)=160*(2) elevado a (5)=00*(2) elevado a (6)=01*(2) elevado a (7)=128La suma es: 151

110111 (binario) = 55 (decimal). Proceso:

Page 5: Operaciones con números binarios

1*(2) elevado a (0)=11*(2) elevado a (1)=21*(2) elevado a (2)=40*(2) elevado a (3)=01*(2) elevado a (4)=161*(2) elevado a (5)=32La suma es: 55

 

Decimal a binario

Se divide el número decimal entre 2 cuyo resultado entero se vuelve a dividir entre 2 y así sucesivamente. Una vez llegados al 1 indivisible se cuentan el último cociente, es decir el uno final (todo número binario excepto el 0 empieza por uno), seguido de los residuos de las divisiones subsiguientes. Del más reciente hasta el primero que resultó. Este número será el binario que buscamos. A continuación se puede ver un ejemplo con el número decimal 100 pasado a binario.

100 |_2 0 50 |_2 0 25 |_2 --> 100 1100100 1 12 |_2 0 6 |_2 0 3 |_2 1 1

Otra forma de conversión consiste en un método parecido a la factorización en números primos. Es relativamente fácil dividir cualquier número entre 2. Este método consiste también en divisiones sucesivas. Dependiendo de si el número es par o impar, colocaremos un cero o un uno en la columna de la derecha. Si es impar, le restaremos uno y seguiremos dividiendo por dos, hasta llegar a 1. Después sólo nos queda tomar el último resultado de la columna izquierda (que siempre será 1) y todos los de la columna de la derecha y ordenar los dígitos de abajo a arriba. Y luego se haría un cuadro con las potencias con el resultado.

Ejemplo:

100|0 50|0 25|1 --> 1, 25-1=24 y seguimos dividiendo por 2 12|0 6|0 3|1 1|1 --> 100 1100100

Page 6: Operaciones con números binarios

Y también tenemos otro método el método de distribución en el que distribuimos el número decimal y podemos tener el resultado en binario, trabaja de la siguiente manera tenemos el número 151 lo que tenemos que hacer es distribuir este número buscando el número más próximo; en este caso es 128 así que en la casilla donde hay capacidad de contener el número que tenemos lo vamos marcando. y en las casillas que no empleamos las marcaremos con un 0.

Ejemplo:

2^0= 1|1 2^1= 2|1 2^2= 4|1 2^3= 8|0 2^4= 16|1 2^5= 32|0 2^6= 64|0 2^7= 128|1 128+16+4+2+1=151 2^8= 256|0

Y sucesivos.

 

Binario a octal

Para realizar la conversión de binario a octal, realice lo siguiente:

1) Agrupe la cantidad binaria en grupos de 3 en 3 iniciando por el lado derecho. Si al terminar de agrupar no completa 3 dígitos, entonces agregue ceros a la izquierda.

2) Posteriormente vea el valor que corresponde de acuerdo a la tabla:

Número en binario

000 001 010 011 100 101 110 111

Número en octal 0 1 2 3 4 5 6 7

3) La cantidad correspondiente en octal se agrupa de izquierda a derecha.

Ejemplos:

110111 (binario) = 67 (octal). Proceso:

Page 7: Operaciones con números binarios

111 = 7110 = 6Agrupe de izquierda a derecha: 67

11001111 (binario) = 317 (octal). Proceso:

111 = 7001 = 111 entonces agregue un cero, con lo que se obtiene 011 = 3Agrupe de izquierda a derecha: 317

1000011 (binario) = 103 (octal). Proceso:

011 = 3000 = 01 entonces agregue 001 = 1Agrupe de izquierda a derecha: 103.

 

Octal a binario

Cada dígito octal se lo convierte en su binario equivalente de 3 bits y se juntan en el mismo orden. Ejemplo:

247 (octal) = 010100111 (binario). El 2 en binario es 10, pero en binario de 3 bits es Oc(2) = B(010); el Oc(4) = B(100) y el Oc(7) = (111), luego el número en binario será 010100111.

Binario a hexadecimal

Para realizar la conversión de binario a hexadecimal, realice lo siguiente:

1) Agrupe la cantidad binaria en grupos de 4 en 4 iniciando por el lado derecho. Si al terminar de agrupar no completa 4 dígitos, entonces agregue ceros a la izquierda.

2) Posteriormente vea el valor que corresponde de acuerdo a la tabla:

Número en binari

o

0000

0001

0010

0011

0100

0101

0110

0111

1000

1001

1010

1011

1100

1101

1110

1111

Page 8: Operaciones con números binarios

Número en hexadecimal

0 1 2 3 4 5 6 7 8 9 A B C D E F

3) La cantidad correspondiente en hexadecimal se agrupa de izquierda a derecha.

Ejemplos:

110111010 (binario) = 1BA (hexadecimal). Proceso:

1010 = A1011 = B1 entonces agregue 0001 = 1Agrupe de izquierda a derecha: 1BA

11011110101 (binario) = 6F5 (hexadecimal). Proceso:

0101 = 51111 = F110 entonces agregue 0110 = 6Agrupe de izquierda a derercha: 6F5

Hexadecimal a binario

Ídem que para pasar de hexadecimal a binario, solo que se remplaza por el equivalente de 4 bits, como de octal a binario.

Tabla de conversión entre decimal, binario, hexadecimal, octal, BCD, Exceso 3 y Gray o Reflejado

Decimal Binario Hexadecimal OctalBCD

Exceso 3 Gray o Reflejado

0 0000 0 0 0000 0011 0000

1 0001 1 1 0001 0100 0001

2 0010 2 2 0010 0101 0011

Page 9: Operaciones con números binarios

3 0011 3 3 0011 0110 0010

4 0100 4 4 0100 0111 0110

5 0101 5 5 0101 1000 0111

6 0110 6 6 0110 1001 0101

7 0111 7 7 0111 1010 0100

8 1000 8 10 1000 1011 1100

9 1001 9 11 1001 1100 1101

10 1010 A 12

11 1011 B 13

12 1100 C 14

13 1101 D 15

14 1110 E 16

15 1111 F 17

http://centros.edu.xunta.es/iesmanuelchamosolamas/electricidade/fotos/numeracion.htm

Page 10: Operaciones con números binarios

Binary Number Representation System

Note: n**m means n raised to the power m

Basics

Binary numbers are simply numbers represented in base 2, as opposed to decimal (base 10).

So, in a binary number such as 1011 ^^^^ ||||-- represents 1 * 2**0 = 1 * 1 |||---represents 1 * 2**1 = 1 * 2 ||---represents 0 * 2**2 = 0 * 4 |---represents 1 * 2**3 = 1 * 8

For a total of 11 decimal.

The smallest positive binary integer (in 8-bit format) is 00000000, or decimal 0.

The largest number is obviously (is it obvious? it should be) 11111111, which a few moments' thought will show you is equivalent to:

2**7 + 2**6 + 2**5 + 2**4 + 2**3 + 2**2 + 2**1 + 2**0 = 255 decimal or 2**8-1.

Coincidence?

No. Consider that the number 1 greater than 11111111 would be 100000000 (which takes 9 bits).

This is evidently 2**8, and so we can see that the largest positive number we can represent in n bits is 2**(n-1) - 1.

Conversions

1. From decimal to binary

Simply repeatedly divide the original number by two, noting all the remainders. The answer is the remainders strung together from left to right.

Example: what is 106 decimal represented in binary?

Page 11: Operaciones con números binarios

2| 106 ----- 2| 53 r 0 ---- 2| 26 r 1 ---- 2| 13 r 0 ---- 2| 6 r 1 --- 2| 3 r 0 --- 2| 1 r 1 --- 0 r 1

Reading the remainders from bottom (right) to top (left) we get: 1101010

2. From binary to decimal

This is even easier. Simply recall that each bit, reading from right to left, represents one higher power of 2. So the rightmost bit represents multiples of 2**0 (i.e. 1), the next multiples of 2**1 (i.e. 2)

So 1101010 = 1 * 2**6 + 1 * 2**5 + 1 * 2**3 + 1 * 2**1 (leaving out the zeros)

= 64 + 32 + 8 + 2

= 106 decimal

QED.

Arithmetic

Binary arithmetic is simple, especially addition.

Here is the addition table for binary:

+ | 0 1--------0 | 0 11 | 1 0C

Where the C means there is a "carry" out of 1 to the left.

So 0101 = 5 decimal + 0011 = 3 decimal

----1000 = 8 decimal

Page 12: Operaciones con números binarios

Subtraction is similarly easy. Here is the subtraction table for binary:

- | 0 1--------0 | 0 1B1 | 1 0

Where the B means there is a "borrow" from the left. So:

0101 = 5 decimal - 0011 = 3 decimal

----0010 = 2 decimal

Multiplication is even simpler. Here is the multiplication table for binary:

* | 0 1--------0 | 0 01 | 0 1

Here is an example of long multiplication - done both British and North American ways.

0011 = 3 decimal * 0101 = 5 decimal

----0011

+ 001100 ------ 001111 = 15 decimal

or

0011 = 3 decimal * 0101 = 5 decimal

---- 001100 + 0011 ------ 001111 = 15 decimal

Negative numbers

The above applies to positive numbers, but how can we represent a negative number? We cannot use a '-' sign because all we can store in the computer is zeros and ones.

There are three methods which have been used. The last is still in use today.

For the sake of simplicity all numbers in the following discussion are 8 bits long. The arguments apply to any length of binary number.

Page 13: Operaciones con números binarios

1. Signed Magnitude

With this system the leftmost bit is not considered part of the number, but as a representation of its sign:

o 0 => positiveo 1 => negative

The remaining n-1 (in our case 7) bits represent the number - the magnitude.

So: 00000101 would be 5 decimal

and 10000101 would be -5 decimal.

Unfortunately there are a few problems with this. Firstly consider zero.

00000000 represents 0

but so does

10000000 (-0 to be precise)

This is inconvenient as it complicates the circuitry. We should like to be able to compare two numbers (a very common operation) by saying: "if the bit patterns are the same the two numbers have the same value; if they are different then they have different values."

Unfortunately the second half of this is not true for signed magnitude binary numbers: the two patterns could represent +0 and -0, so extra circuitry must be incorporated to test for this.

Secondly, arithmetic with signed magnitude is complex. Although adding two positive numbers is not a problem (unless the result overflows into the sign bit, but we'll worry about that in COMP182   ). But consider adding +6 to -4.

+6 = 00000110-4 = 10000100

If we simply add the bit patterns we shall get:

10001010

Which is -10 decimal, and not the -2 we wanted.

Page 14: Operaciones con números binarios

The answer is simple (!): if the two numbers have the same sign then we can add them (except for the sign bit) and put the common sign bit in the result. Here are two examples:

+3 = 00000011+6 = 00000110-------------+ 00001001 = +9 decimal

-7 = 10000111-4 = 10000100-------------+ 10001011 = -11 decimal

If the two numbers are of opposite signs - i.e one plus and one minus - then the rule is: subtract the smaller magnitude from the larger and give the result the sign of the larger original number.

+3 = 00000011-6 = 10000110-------------+ 10000011 = -3

Signed magnitude therefore has two strikes against it: 1) the arithmetic circuitry has to be more complex to deal with the problem of oppositely-signed numbers; 2) there are two representations of zero.

2. 1's Complement

In the 1's complement system you get a negative number simply by inverting ('flipping') every bit in the positive version.

Thus 00000101

is +5 decimal and so

11111010

is -5 decimal.

The advantage of 1's complement is that arithmetic is now so much simpler: we don't have to worry about opposite signs - it will all 'come out in the wash'. The rule for adding numbers in 1's complement is simple: just add the two numbers together plus if there is a carry out to the left this is added in as a 1 at the right. (Simpler view: the left carry out is added at the right, whether it's a 1 or a 0).

Example:

Page 15: Operaciones con números binarios

+3 = 00000011+6 = 00000110-------------+ 00001001 = +9 decimal

+7 = 00000111+4 = 00000100-------------+ 00001011 = +11 decimal

now -7 = 11111000and -4 = 11111011

-7 = 11111000-4 = 11111011 1 <- the 'end around carry' bit from the left -------------+ 11110100 = -11 decimal (flip the bits and you get

00001011 or +11 decimal)

If the two numbers are of opposite signs - i.e one plus and one minus the the same method works:

+7 = 00000111-4 = 11111011 1 <- 'eac'------------- 00000011 = +3 decimal

-7 = 11111000+4 = 00000100 0 <- zero 'eac' here------------- 11111100 = -3 decimal (flip the bits and you get

00000011 = +3 decimal)

Now, what if we add

+7 = 00000111-7 = 11111000 0 <- again zero eac------------- 11111111 = -0 (flip the bits and you get 00000000 = +0)

So, although the arithmetic works a treat we still have two representations for zero.

3. 2's complement

With 2's complement arithmetic we make the converson from positive to negative (and vice-versa) slightly more complex. To go from one to the other now takes two stages: 1) flip all the bits 2) add 1. (This is almost like adding in the end around carry ahead of time).

Page 16: Operaciones con números binarios

+4 = 00000100

so to generate -4

1) 111110112) + 1 -------- 11111100

And +7 = 00000111

1) 111110002) + 1 -------- 11111001 = -7

Now we can do arithmetic as usual, ignoring carries and sign.

+3 = 00000011+6 = 00000110-------------+ 00001001 = +9 decimal

-7 = 11111001-4 = 11111100-------------+ 11110101 = +11 decimal (flip: 00001010 + 1 = 00001011 =

+11 decimal)

(Don't forget we ignored the carry out to the left).

If the two numbers are of opposite signs - i.e one plus and one minus the the same method works:

+7 = 00000111-4 = 11111100------------- 00000011 = +3 decimal

-7 = 11111001+4 = 00000100------------- 11111101 = -3 decimal (flip: 00000010 + 1 = 00000011 =

+3 decimal)

Now, what if we add

+7 = 00000111-7 = 11111001------------- 00000000 = 0

Interesting! Now what if we try to generate -0 from +0?

+0 = 00000000 11111111 + 1

Page 17: Operaciones con números binarios

-------- 00000000

Aha! In 2's complement we:

1. have simpler arithmetic and2. only have a single representation for zero

This is why 2's complement is today exclusively used for integer binary arithmetic.

A tip

In order to convert say 10011011 from binary to decimal we must first ask whether the bit pattern represents a signed or unsigned binary number. There is absolutely nothing in the bit pattern itself that tells us - it is important that you appreciate this. (In fact those 8 bits might represent an ASCII or EBCDIC character for all we know).

If it is unsigned then the usal conversion method (rightmost bit represents 1, next 2, next 4 etc.) works. E.g.:

10011011 ^^^^^^^^ ||||||||-- represents 1 * 2**0 = 1 * 1 |||||||---represents 1 * 2**1 = 1 * 2 ||||||---represents 0 * 2**2 = 0 * 4 |||||---represents 1 * 2**3 = 1 * 8 ||||---represents 1 * 2**4 = 1 * 16 |||---represents 0 * 2**5 = 0 * 32 ||---represents 0 * 2**6 = 0 * 64 |---represents 1 * 2**7 = 1 * 128

If it is a 2's complement signed number then we can either use the algorithm described above (flip bits and add 1) to turn it into its positive value (any binary number with its leftmost bit 1 will be negative: this is true - albeit for different reasons - for all three systems).

But then we still have to convert the resulting positive number.

On the other hand, we can view a 2's complement number like this:

10011011 ^^^^^^^^ ||||||||-- represents 1 * 2**0 = 1 * 1 |||||||---represents 1 * 2**1 = 1 * 2 ||||||---represents 0 * 2**2 = 0 * 4 |||||---represents 1 * 2**3 = 1 * 8

Page 18: Operaciones con números binarios

||||---represents 1 * 2**4 = 1 * 16 |||---represents 0 * 2**5 = 0 * 32 ||---represents 0 * 2**6 = 0 * 64 |---represents 1 * -(2**7) = 1 * -128

Notice that the leftmost bit's negativity (if you will) now completely outweighs the positivity of all the others combined (so if the leftmost bit is a 1 the number must be negative).

So the bit pattern above, if a positive number, represents 155 (= 1 + 2 + 8 + 16 + 128)

But if it is a 2's complement number it is negative and has the value -101 (= 1 + 2 + 8 + 16 + -128).

We can confirm this by using the slow algorithm:

10011011

flip: 01100100 + 1--------01100101 = 1 + 4 + 32 + 64 = 101

So the original bit pattern represented -101 as claimed.

(And some days the bear eats you).