Binary 1's and 2's Complement
The binary 1's and 2's complement is carried out on binary numbers to simplify the digital circuits on subtraction operation works as same as addition operation. It is also used in signed decimal to binary conversion.
One's or 1's Complement
- Binary Inversion - binary bits flipping, if a bit is 1, it is inverted into 0 or if a bit is 0, it is inverted into 1.
- One's Complement - Binary inversion is carried out on each bit in the binary numbers and resultant binary numbers from this operation called One's complement of the binary numbers.
Binary One's/1's Complement -Example
find one's complement for given binary number = 01010 invert each bit, i.e 1 into 0 and 0 into 1. 01010 - one's complement - 10101
Binary Two's/2's Complement
Two's Complement on the binary numbers carried out by two binary operation. They are, One's complement and a binary addition.
- Take one's complement on binary numbers
- add a binary bit 1 with resultant one's complement
2's or Two's Complement -Example
find one's complement for given binary number = 01010 invert each bit, i.e 1 into 0 and 0 into 1. 01010 - one's complement - 10101 binary addition - add a binary bit 1 with one's complement result 10101 00001 ------- Two'complement 10110
Binary One's and Two's Complement - Java program
import java.util.Scanner;
public class Complement
{
public static String ones(String binary) {
StringBuffer sbuf = new StringBuffer();
for(int n=0;n<binary.length();n++) {
char c = binary.charAt(n)=='1' ? '0' : '1';
sbuf.append(c);
}
return sbuf.toString();
}
public static String twos(String binary) {
String onbinary = Complement.ones(binary);
StringBuffer sbuf = new StringBuffer(onbinary);
int addone=1; int n=0;
for(n=binary.length()-1;n>=0;n--)
{
int abit =Integer.parseInt( onbinary.charAt(n)+"" );
int reminder= (abit+addone) % 2 ;
addone = (abit+addone) /2 ;
sbuf.replace(n, n+1, reminder+"");
if ( addone==0 )
break;
}
return sbuf.toString();
}
public static void main(String[] args)
{
Scanner sc =new Scanner(System.in);
System.out.println("n Binary One's and Two's Compliments");
System.out.println("Enter binary numbers :");
String binary = sc.nextLine();
sc.close();
String onesbinary=Complement.ones(binary);
System.out.println("\n Binary numbers - One's Compliment ");
System.out.println(onesbinary);
String twosbinary=Complement.twos(binary);
System.out.println("\n Binary numbers - Two's Compliment ");
System.out.println(twosbinary);
}
}
Binary Complement - Java code output
Binary One's and Two's Compliments Enter binary numbers : 010100 Binary numbers - One's Compliment 101011 Binary numbers - Two's Compliment 101100
Comments
Post a Comment