Query:
Take two 512 bit numbers passed as strings. don't use biginteger!
convert them to binary without using parseInt or toString functions.! you may use char array and byte arrays.
then add these two binary numbers using binary addition logic.
display the result in decimal format back again.
Is it possible to perform this operation like this!!if yes,then please tell how should i approach with my existing code.
thanks.
package bytearrayopeations;
import java.math.BigInteger;
public class binaryadding {
public static void main(String[] args) {
BigInteger a = new BigInteger("123456");
BigInteger b = new BigInteger("5121");
String bb1 = a.toString(2);
String bb2 = b.toString(2);
String ss1 = null;
String ss2 = null;
String result = "";
String carry="0";
System.out.println("first value=" +bb1);
System.out.println("second value=" +bb2);
int k=bb1.length();
int h=bb2.length();
System.out.println("length 1="+ k);
System.out.println("length 2=" +h);
int p=h-k;
//System.out.println("difference=" +p);
int q=k-h;
//System.out.println("difference 2=" +q);
if(h==k)
{}
else if(h>k)
{
for(int i=0;i<p;i++)
{
bb1="0"+bb1;
}
System.out.println("new value of first=" +bb1);
}
else if(h<k)
{
for(int i=0;i<q;i++)
{
bb2="0"+bb2;
}
System.out.println("new value of second=" +bb2);
}
StringBuffer sb1=new StringBuffer(bb1);
StringBuffer sb2=new StringBuffer(bb2);
bb1=sb1.reverse().toString();
bb2=sb2.reverse().toString();
//System.out.println("rev. buffer1=" +bb1);
//System.out.println("rev. buffer2=" +bb2);
for(int i=0;i<bb1.length();i++)
{
ss1=bb1.substring(i,i+1);
ss2=bb2.substring(i,i+1);
System.out.println("value1=" + ss1 + " " + "value2=" + ss2);
if (ss1.equals("0") && ss2.equals("0"))
{
if (carry.equals("0"))
{
result+="0";
}
else
{
result+="1";
}
}
else if (ss1.equals("1") && ss2.equals("1"))
{
if (carry.equals("0"))
{
result+="0";
carry="1";
}
else
{
result+="1";
carry="1";
}
}
else if (ss1.equals("0") && ss2.equals("1"))
{
if (carry.equals("0"))
{
result+="1";
carry="0";
}
else
{
result+="0";
carry="1";
}
}
else if (ss1.equals("1") && ss2.equals("0"))
{
if (carry.equals("0"))
{
result+="1";
carry=" 0";
}
else
{
result+="0";
carry="1";
}
}
System.out.println("sum=" +result + " " + "carry" + carry);
}
result+=carry;
StringBuffer sb3=new StringBuffer(result);
result=sb3.reverse().toString();
System.out.println("result is " +result);
System.out.println("Binary = "+ result + ", Decimal = "+Integer.parseInt(result,2));
}
}