SlideShare a Scribd company logo
Java binary subtraction
import java.io.*;
class BinarySubtraction{
public static int sign=0;
public static void main(String args[])throws IOException{
String result=new String();
String twosComp=new String();
char borrow='0';
int i;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Minuend: ");
String minuend=br.readLine();
System.out.print("Subtrahend: ");
String subtrahend=br.readLine();
if(validate(minuend) && validate(subtrahend)){
if(minuend.length()>8 || subtrahend.length()>8)
System.out.println("Maximum allowed length: 8");
else{
twosComp=get2sComplement(subtrahend);
System.out.println("Two's complement of "+subtrahend+" is
"+twosComp);
result=add(minuend, twosComp);
if(sign==1)
result="-"+result;
System.out.println("Result: "+result);
}
}
else
System.out.println("Invalid Binary Number!");
}
public static boolean validate(String binaryValue){
for(int i=0;i<binaryValue.length();i++)
if(binaryValue.charAt(i)!='0' && binaryValue.charAt(i)!='1')
return false;
return true;
}
public static String get2sComplement(String binaryVal){
String onesComp=new String();
String twosComp=new String();
char carry='0';
int i;
//finding one's complement--------------------------------
for(i=0;i<binaryVal.length();i++){
if(binaryVal.charAt(i)=='0')
onesComp=onesComp+"1";
else onesComp=onesComp+"0";
} //---------------------------------------------------------
char lsb=onesComp.charAt(onesComp.length()-1);
if(lsb=='1'){
twosComp="0"+twosComp; carry='1';
}
else twosComp="1"+twosComp;
for(i=onesComp.length()-2;i>=0;i--){
char digit=onesComp.charAt(i);
if(carry=='0' && digit=='0')
twosComp="0"+twosComp;
else if(carry=='0' && digit=='1')
twosComp="1"+twosComp;
else if(carry=='1' && digit=='0'){
twosComp="1"+twosComp;
carry='0';
}
else{
twosComp="0"+twosComp;
carry='1';
}
}
return twosComp;
}
public static String add(String m, String s){
String sum=new String();
int i;
char carry='0';
for(i=m.length()-1;i>=0;i--){
if(m.charAt(i)=='0' && s.charAt(i)=='0' && carry=='0')
sum="0"+sum;
else if(m.charAt(i)=='0' && s.charAt(i)=='0' && carry=='1'){
sum="1"+sum;
carry='0';
}
else if(m.charAt(i)=='0' && s.charAt(i)=='1' && carry=='0')
sum="1"+sum;
else if(m.charAt(i)=='0' && s.charAt(i)=='1' && carry=='1'){
sum="0"+sum;
carry='1';
}
else if(m.charAt(i)=='1' && s.charAt(i)=='0' && carry=='0')
sum="1"+sum;
else if(m.charAt(i)=='1' && s.charAt(i)=='0' && carry=='1'){
sum="0"+sum;
carry='1';
}
else if(m.charAt(i)=='1' && s.charAt(i)=='1' && carry=='0'){
sum="0"+sum;
carry='1';
}
else if(m.charAt(i)=='1' && s.charAt(i)=='1' && carry=='1'){
sum="1"+sum;
carry='1';
}
}
return sum;
}
}
C++ binaru subtractin
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0){ }
void input()
{
cout<<"Enter real and imaginary parts respectively: ";
cin>>real;
cin>>imag;
}
Complex operator - (Complex c2) /* Operator Function */
{
Complex temp;
temp.real=real-c2.real;
temp.imag=imag-c2.imag;
return temp;
}
void output()
{
if(imag<0)
cout<<"Output Complex number: "<<real<<imag<<"i" ;
else
cout<<"Output Complex number: "<<real<<"+"<<imag<<"i";
}
};
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number:n";
c1.input();
cout<<"Enter second complex number:n";
c2.input();
/* In case of operator overloading of binary operators in C++ programming,
the object on right hand side of operator is always assumed as argument by
compiler. */
result=c1-c2; /* c2 is furnised as an argument to the operator function. */
result.output();
return 0;
}
JAVA Multiply hexa
package com.datastructute.arraystring;
public class hexadecimal {
public static void main(String[] args) {
System.out.println(multiplyHex("AE08FE2111111111", "BF"));
System.out.println(multiplyHex("DF", "BC")); // A3C4
System.out.println(multiplyHex("ADF398", "BA48")); // 7e93e8f2c0
// Test Screnarios
System.out.println(multiplyHex(null, null));
System.out.println(multiplyHex(" ", " "));
System.out.println(multiplyHex("hyh", "hyhy"));
System.out.println(multiplyHex("abyh", "ashyhy"));
System.out.println(multiplyHex("-1-1-1", "-1-1-1"));
System.out.println(multiplyHex("AE08FE2111111111AE08FE2AE08FE21111
11111AE08FE2111111111AE08FE2111111111AE08FE2111111111AE08FE2
111111111AE08FE2111111111AE08FE2111111111AE08FE2111111111AE0
8FE2111111111AE08FE2111111111AE08FE2111111111AE08FE2111111111
AE08FE2111111111AE08FE2111111111AE08FE2111111111AE08FE211111
1111AE08FE21111111111111AE08FE2111111111AE08FE21111111111111
AE08FE21111AE08FE211111111111111",
"AE0AE08FE21111111118FE2111111111AE08FE2111111111"));
}
public static String multiplyHex(String str1, String str2) {
if(str1 == null || str2 == null)
return "Null values are not accepted.";
char[] hex1 = str1.toCharArray();
char[] hex2 = str2.toCharArray();
int[][] ArrHexMatrix;
int arrLength = hex1.length + hex2.length;
int arrIndexLength = hex1.length + hex2.length - 1;
int lines = hex2.length;
ArrHexMatrix = new int[hex2.length][arrLength];
int mod = 0;
int carry = 0;
int count = 0;
int index = 0;
for (int i = lines - 1; i >= 0; i--) {
carry = 0;
count = 0;
for (int j = hex1.length - 1; j >= 0; j--) {
try {
if(getInt(hex2[i])==-1 || getInt(hex1[j])==-1)
return "Wrong chracter";
mod = (getInt(hex2[i]) * getInt(hex1[j]) + carry) % 16;
carry = ((getInt(hex2[i]) * getInt(hex1[j])) + carry) / 16;
if (j == 0) {
ArrHexMatrix[index][arrIndexLength - count - index] = mod;
ArrHexMatrix[index][arrIndexLength - count - 1 - index] =
carry;
} else {
ArrHexMatrix[index][arrIndexLength - count - index] = mod;
}
} catch (Exception e) {
e.printStackTrace();
}
count++;
}
index++;
}
int sum = 0;
mod = 0;
carry = 0;
count = 0;
char[] total = new char[arrLength];
for (int i = arrLength - 1; i >= 0; i--) {
sum = 0;
for (int j = 0; j < lines; j++) {
sum += ArrHexMatrix[j][i];
}
mod = (sum + carry) % 16;
carry = (sum + carry) / 16;
try {
total[i] = getChar(mod);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return String.valueOf(total);
}
private static int getInt(char chr) {
switch (chr) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'A':
return 10;
case 'B':
return 11;
case 'C':
return 12;
case 'D':
return 13;
case 'E':
return 14;
case 'F':
return 15;
default:
return -1;
}
}
private static char getChar(int val) throws Exception {
switch (val) {
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
case 10:
return 'A';
case 11:
return 'B';
case 12:
return 'C';
case 13:
return 'D';
case 14:
return 'E';
case 15:
return 'F';
default:
throw new Exception();
}
}
}

More Related Content

PDF
Network security
PDF
The Art of Clean Code
PDF
JVM Mechanics
PDF
JVM Mechanics: Understanding the JIT's Tricks
PDF
Coscup2021 - useful abstractions at rust and it's practical usage
PDF
Coscup2021-rust-toturial
PDF
Java Performance Puzzlers
PDF
Rainer Grimm, “Functional Programming in C++11”
Network security
The Art of Clean Code
JVM Mechanics
JVM Mechanics: Understanding the JIT's Tricks
Coscup2021 - useful abstractions at rust and it's practical usage
Coscup2021-rust-toturial
Java Performance Puzzlers
Rainer Grimm, “Functional Programming in C++11”

What's hot (20)

PDF
C++ L06-Pointers
PDF
Arduino coding class part ii
DOCX
C programs
PPTX
Groovy
PDF
Arduino coding class
PDF
C Code and the Art of Obfuscation
PPT
Advance features of C++
PPT
Lo Mejor Del Pdc2008 El Futrode C#
PDF
Introducción a Elixir
PDF
Bartosz Milewski, “Re-discovering Monads in C++”
PDF
Asssignment2
PDF
The Ring programming language version 1.8 book - Part 35 of 202
PDF
Lambda expressions in C++
PDF
Go vs C++ - CppRussia 2019 Piter BoF
TXT
Los dskn
PPTX
Operator overloading2
PDF
Program Language - Fall 2013
DOC
Ds 2 cycle
PDF
The Ring programming language version 1.5.4 book - Part 30 of 185
PDF
A tour of Python
C++ L06-Pointers
Arduino coding class part ii
C programs
Groovy
Arduino coding class
C Code and the Art of Obfuscation
Advance features of C++
Lo Mejor Del Pdc2008 El Futrode C#
Introducción a Elixir
Bartosz Milewski, “Re-discovering Monads in C++”
Asssignment2
The Ring programming language version 1.8 book - Part 35 of 202
Lambda expressions in C++
Go vs C++ - CppRussia 2019 Piter BoF
Los dskn
Operator overloading2
Program Language - Fall 2013
Ds 2 cycle
The Ring programming language version 1.5.4 book - Part 30 of 185
A tour of Python
Ad

Similar to Java binary subtraction (20)

PDF
Problem 2.19. How much time is required to add or subtract two large.pdf
PDF
Mcs 012 soved assignment 2015-16
PDF
I need the code for a Java programming project. Allow the user to ty.pdf
PDF
Computer Architecture: ARITHMETIC FOR COMPUTERS
DOCX
Import java
PPTX
CA Unit ii
PPTX
Computer Architecture
PPTX
Computer Architecture
PDF
Data structuresUsing java language and develop a prot.pdf
PPT
Stack, queue and hashing
PPT
ch3a-binary-numbers.ppt
PPT
Mba admission in india
PPTX
ARITHMETIC FOR COMPUTERS
PPTX
บทที่ 3 พื้นฐานภาษา Java
PPTX
TCS_Digital_Advanced_Coding_Student copy.pptx
PDF
Integration Project Inspection 3
PPTX
Virtusa questions placement preparation guide
PDF
Bitwise complement operator
PPTX
OBJECT ORIENTED PROGRAMMIING LANGUAGE PROGRAMS
PPTX
lab programs on java and dbms for students access
Problem 2.19. How much time is required to add or subtract two large.pdf
Mcs 012 soved assignment 2015-16
I need the code for a Java programming project. Allow the user to ty.pdf
Computer Architecture: ARITHMETIC FOR COMPUTERS
Import java
CA Unit ii
Computer Architecture
Computer Architecture
Data structuresUsing java language and develop a prot.pdf
Stack, queue and hashing
ch3a-binary-numbers.ppt
Mba admission in india
ARITHMETIC FOR COMPUTERS
บทที่ 3 พื้นฐานภาษา Java
TCS_Digital_Advanced_Coding_Student copy.pptx
Integration Project Inspection 3
Virtusa questions placement preparation guide
Bitwise complement operator
OBJECT ORIENTED PROGRAMMIING LANGUAGE PROGRAMS
lab programs on java and dbms for students access
Ad

Recently uploaded (20)

DOCX
Euro SEO Services 1st 3 General Updates.docx
PPTX
The Marketing Journey - Tracey Phillips - Marketing Matters 7-2025.pptx
PDF
Reconciliation AND MEMORANDUM RECONCILATION
PDF
Laughter Yoga Basic Learning Workshop Manual
PDF
Chapter 5_Foreign Exchange Market in .pdf
PDF
Power and position in leadershipDOC-20250808-WA0011..pdf
PDF
IFRS Notes in your pocket for study all the time
PDF
Solara Labs: Empowering Health through Innovative Nutraceutical Solutions
PDF
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
PPT
340036916-American-Literature-Literary-Period-Overview.ppt
PPTX
Dragon_Fruit_Cultivation_in Nepal ppt.pptx
PDF
How to Get Business Funding for Small Business Fast
PPTX
HR Introduction Slide (1).pptx on hr intro
PPTX
Belch_12e_PPT_Ch18_Accessible_university.pptx
PDF
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
PDF
MSPs in 10 Words - Created by US MSP Network
PDF
Roadmap Map-digital Banking feature MB,IB,AB
DOCX
unit 1 COST ACCOUNTING AND COST SHEET
PPTX
Principles of Marketing, Industrial, Consumers,
PDF
BsN 7th Sem Course GridNNNNNNNN CCN.pdf
Euro SEO Services 1st 3 General Updates.docx
The Marketing Journey - Tracey Phillips - Marketing Matters 7-2025.pptx
Reconciliation AND MEMORANDUM RECONCILATION
Laughter Yoga Basic Learning Workshop Manual
Chapter 5_Foreign Exchange Market in .pdf
Power and position in leadershipDOC-20250808-WA0011..pdf
IFRS Notes in your pocket for study all the time
Solara Labs: Empowering Health through Innovative Nutraceutical Solutions
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
340036916-American-Literature-Literary-Period-Overview.ppt
Dragon_Fruit_Cultivation_in Nepal ppt.pptx
How to Get Business Funding for Small Business Fast
HR Introduction Slide (1).pptx on hr intro
Belch_12e_PPT_Ch18_Accessible_university.pptx
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
MSPs in 10 Words - Created by US MSP Network
Roadmap Map-digital Banking feature MB,IB,AB
unit 1 COST ACCOUNTING AND COST SHEET
Principles of Marketing, Industrial, Consumers,
BsN 7th Sem Course GridNNNNNNNN CCN.pdf

Java binary subtraction

  • 1. Java binary subtraction import java.io.*; class BinarySubtraction{ public static int sign=0; public static void main(String args[])throws IOException{ String result=new String(); String twosComp=new String(); char borrow='0'; int i; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Minuend: "); String minuend=br.readLine(); System.out.print("Subtrahend: "); String subtrahend=br.readLine(); if(validate(minuend) && validate(subtrahend)){ if(minuend.length()>8 || subtrahend.length()>8) System.out.println("Maximum allowed length: 8"); else{ twosComp=get2sComplement(subtrahend); System.out.println("Two's complement of "+subtrahend+" is "+twosComp); result=add(minuend, twosComp); if(sign==1) result="-"+result; System.out.println("Result: "+result); } } else System.out.println("Invalid Binary Number!"); } public static boolean validate(String binaryValue){ for(int i=0;i<binaryValue.length();i++) if(binaryValue.charAt(i)!='0' && binaryValue.charAt(i)!='1') return false; return true; } public static String get2sComplement(String binaryVal){ String onesComp=new String(); String twosComp=new String(); char carry='0'; int i; //finding one's complement-------------------------------- for(i=0;i<binaryVal.length();i++){ if(binaryVal.charAt(i)=='0') onesComp=onesComp+"1"; else onesComp=onesComp+"0"; } //--------------------------------------------------------- char lsb=onesComp.charAt(onesComp.length()-1); if(lsb=='1'){ twosComp="0"+twosComp; carry='1'; } else twosComp="1"+twosComp; for(i=onesComp.length()-2;i>=0;i--){ char digit=onesComp.charAt(i); if(carry=='0' && digit=='0') twosComp="0"+twosComp; else if(carry=='0' && digit=='1') twosComp="1"+twosComp; else if(carry=='1' && digit=='0'){ twosComp="1"+twosComp; carry='0'; } else{ twosComp="0"+twosComp; carry='1'; } } return twosComp; } public static String add(String m, String s){ String sum=new String(); int i; char carry='0'; for(i=m.length()-1;i>=0;i--){ if(m.charAt(i)=='0' && s.charAt(i)=='0' && carry=='0') sum="0"+sum; else if(m.charAt(i)=='0' && s.charAt(i)=='0' && carry=='1'){ sum="1"+sum; carry='0'; } else if(m.charAt(i)=='0' && s.charAt(i)=='1' && carry=='0') sum="1"+sum; else if(m.charAt(i)=='0' && s.charAt(i)=='1' && carry=='1'){ sum="0"+sum; carry='1'; } else if(m.charAt(i)=='1' && s.charAt(i)=='0' && carry=='0') sum="1"+sum; else if(m.charAt(i)=='1' && s.charAt(i)=='0' && carry=='1'){ sum="0"+sum; carry='1'; } else if(m.charAt(i)=='1' && s.charAt(i)=='1' && carry=='0'){ sum="0"+sum; carry='1'; } else if(m.charAt(i)=='1' && s.charAt(i)=='1' && carry=='1'){ sum="1"+sum; carry='1'; } } return sum; } } C++ binaru subtractin #include <iostream> using namespace std; class Complex { private: float real; float imag; public: Complex(): real(0), imag(0){ } void input() { cout<<"Enter real and imaginary parts respectively: "; cin>>real; cin>>imag; } Complex operator - (Complex c2) /* Operator Function */ { Complex temp; temp.real=real-c2.real; temp.imag=imag-c2.imag; return temp; } void output() { if(imag<0) cout<<"Output Complex number: "<<real<<imag<<"i" ; else cout<<"Output Complex number: "<<real<<"+"<<imag<<"i"; } }; int main() { Complex c1, c2, result; cout<<"Enter first complex number:n"; c1.input(); cout<<"Enter second complex number:n"; c2.input(); /* In case of operator overloading of binary operators in C++ programming, the object on right hand side of operator is always assumed as argument by compiler. */ result=c1-c2; /* c2 is furnised as an argument to the operator function. */ result.output(); return 0; } JAVA Multiply hexa package com.datastructute.arraystring; public class hexadecimal { public static void main(String[] args) { System.out.println(multiplyHex("AE08FE2111111111", "BF")); System.out.println(multiplyHex("DF", "BC")); // A3C4 System.out.println(multiplyHex("ADF398", "BA48")); // 7e93e8f2c0 // Test Screnarios System.out.println(multiplyHex(null, null)); System.out.println(multiplyHex(" ", " ")); System.out.println(multiplyHex("hyh", "hyhy")); System.out.println(multiplyHex("abyh", "ashyhy")); System.out.println(multiplyHex("-1-1-1", "-1-1-1")); System.out.println(multiplyHex("AE08FE2111111111AE08FE2AE08FE21111 11111AE08FE2111111111AE08FE2111111111AE08FE2111111111AE08FE2 111111111AE08FE2111111111AE08FE2111111111AE08FE2111111111AE0 8FE2111111111AE08FE2111111111AE08FE2111111111AE08FE2111111111 AE08FE2111111111AE08FE2111111111AE08FE2111111111AE08FE211111 1111AE08FE21111111111111AE08FE2111111111AE08FE21111111111111 AE08FE21111AE08FE211111111111111", "AE0AE08FE21111111118FE2111111111AE08FE2111111111")); } public static String multiplyHex(String str1, String str2) { if(str1 == null || str2 == null) return "Null values are not accepted."; char[] hex1 = str1.toCharArray(); char[] hex2 = str2.toCharArray();
  • 2. int[][] ArrHexMatrix; int arrLength = hex1.length + hex2.length; int arrIndexLength = hex1.length + hex2.length - 1; int lines = hex2.length; ArrHexMatrix = new int[hex2.length][arrLength]; int mod = 0; int carry = 0; int count = 0; int index = 0; for (int i = lines - 1; i >= 0; i--) { carry = 0; count = 0; for (int j = hex1.length - 1; j >= 0; j--) { try { if(getInt(hex2[i])==-1 || getInt(hex1[j])==-1) return "Wrong chracter"; mod = (getInt(hex2[i]) * getInt(hex1[j]) + carry) % 16; carry = ((getInt(hex2[i]) * getInt(hex1[j])) + carry) / 16; if (j == 0) { ArrHexMatrix[index][arrIndexLength - count - index] = mod; ArrHexMatrix[index][arrIndexLength - count - 1 - index] = carry; } else { ArrHexMatrix[index][arrIndexLength - count - index] = mod; } } catch (Exception e) { e.printStackTrace(); } count++; } index++; } int sum = 0; mod = 0; carry = 0; count = 0; char[] total = new char[arrLength]; for (int i = arrLength - 1; i >= 0; i--) { sum = 0; for (int j = 0; j < lines; j++) { sum += ArrHexMatrix[j][i]; } mod = (sum + carry) % 16; carry = (sum + carry) / 16; try { total[i] = getChar(mod); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return String.valueOf(total); } private static int getInt(char chr) { switch (chr) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'A': return 10; case 'B': return 11; case 'C': return 12; case 'D': return 13; case 'E': return 14; case 'F': return 15; default: return -1; } } private static char getChar(int val) throws Exception { switch (val) { case 0: return '0'; case 1: return '1'; case 2: return '2'; case 3: return '3'; case 4: return '4'; case 5: return '5'; case 6: return '6'; case 7: return '7'; case 8: return '8'; case 9: return '9'; case 10: return 'A'; case 11: return 'B'; case 12: return 'C'; case 13: return 'D'; case 14: return 'E'; case 15: return 'F'; default: throw new Exception(); } } }