# Binary Manipulation

### Conversions

Class:

1. Teacher shows how to produce binary representations for the decimal numbers 6 and 3.

2. Teacher shows how to convert binary to decimal and shows verifies the result 110 produces 6 and 3 produces 11.

• Teacher adds 6 (110) and 3 (11) and verifies the result

### Binary Subtraction

• Teacher subtracts 6 (110) and 3 (11) and verifies the result as 3 (11)

### Sign And Magnitude

• Teacher shows how the fixed point system is used with  the MSB used to represent the sign, 0 for +ve, 1 for –ve

### Twos complement

• Show the +ve representation for 6 and 3

• Show –ve representation of 6 and 3 (Using flip_+1 and copy+1 methods)
• Copy method :
• Going from right to left, copy all digits up to and including the first 1.
• Filp the remaining bits.

• Verify that 6-3 is equivalent to 6 + (-3 ) for an 8 bit two’s complement system.

In twos complement the MSB is taken to be -ve

#### Exercise – The Largest and Smallest magnitude twos complement numbers using 4 bits

Using a 4 bit twos complement system, what’s the

1. Largest +ve number ,
2. Lowest  -ve number

That can be represented?

# Decimal to binary

Task: Create an algorithm which accepts a decimal integer and outputs it’s binary equivalent.

This algorithm was designed and implemented in Flowgorithm:

See the video below for an explanation of how the algorithm works:

The code in C is shown below:

Copy and paste from here:

```#include <stdio.h>
#include <stdlib.h>
#include <string.h>//library needed for string operations

int main()
{
//declare and identify integers
int number, remainder;

//declare, identify and initialize all strings
char  result[20]="";
char  remainderString[20]="";

//initialize all other variables
number=-1;
remainder=-1;

//get input
printf("Enter a number in decimal\n");
scanf("%d", &number);
printf("\n");

while (number!=0)
{
remainder=number%2;

/* #Implementation_Result

Here we implement the following:

result=remainder + result
*/

//first convert the remainder to a string,
//and store the converted data in "remainderString"
itoa(remainder,remainderString,10);

//add "remainderString" to "result" in that order.
//the result of the concatenation is stored in "remainderString"
strcat(remainderString,result);

//now copy our data so far back to "result"
strcpy(result,remainderString);
/*End #Implementation_Result*/

number=number/2;

}

printf("The binary Result is %s \n",result);
return 0;
}

```