# urgent: reading binary numbers bit by bit

ive got to write a software where 2binary numbers are input and added together.

i need to know how to add two binary numbers bit by bit(bit by bit because i need to use the bits later).  there will CARRY digits and SUM digits as a result, but mainly my problem is figuring out how to Store the binary numbers(say x,y) so that i can pick out the bits of the same position and add them.

###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Use an ArrayList to store the number and then start from behind with an loop...

extract the numbers from the arraylist with the get(int i) method or create an itertator from the list.

if you know befor how many digits the number will have you may also want to use e.g int[], String[],...

but keep in mind how the binary calculation works: it might even make sense to calcuate with decimal numbers and then retransform

there are some functions whitch may help a lot e.g

String s = Integer.String toBinaryString(int i); //converts an decimal to its binary in string representation

...
Commented:
What is the size of the binary numbers? 16bits? 32bits?
Java DeveloperCommented:
Commented:
String input = "11111 + 1011011";

String[] tokens = input.split("\\s"); // ["11111", "+", "1011011"]

int maxLen = Math.max( tokens[0].length(), tokens[2].length() );  // 7
int maxIndex = tokens[0].length() > tokens[2].length() ? 0 : 2 ;    // 2
int minIndex = tokens[0].length() < tokens[2].length() ? 0 : 2 ;     // 0
int diffLen = tokens[maxIndex].length() - tokens[minIndex].length();  // 7- 5 = 2

for(int i=0; i<diffLen; i++) tokens[minIndex] = "0"+tokens[minIndex];  // "11111" --> "0011111"

char[] numBits = tokens[0].toCharArray();   // ['0','0','1','1','1','1','1']
char[] adderBits = tokens[2].toCharArray(); // ['1','0','1','1','0','1','1']
// ['1','1','0','1','1','0','1','0']

char[] result = new char[ maxLen + 1 ];      // adding result may have higher length

char zero = '0';
int carry = 0;

for(int i = maxLen-1; i >= 0; i--) {
int num = numBits[i] - zero;     // converse char to int based on relevant value. if i = 6, num = 1
int temp = num + adder + carry;
int r = temp % 2;       // if i = 6, r(esult) = 0
carry = temp >> 1;
result[i+1] = (char)(r + zero);   // if i = 6, result[7] = '0'
}
result[0] = (char)(carry + zero);

System.out.println(input+" = "+new String(result)); // "11111 + 1011011 = 01111010"

Try with it.
G noon
Commented:
Another way to solve is to use the bit operation and using Long variable to store:
this only works if the input bits length is less than 64 (max size of long = 64 bit)

String sInput1 = "1100";  //value 12
String sInput2 = "0110"; //value 6

Long input1 = Long.parseLong(sInput1, 2);
Long input2 = Long.parseLong(sInput2, 2);

to carry but operation you can use the &, |, ^ bitwise operators or the shift left, right operator <<, >>
example:
Long input3 = input1 & input2;
System.out.println(Long.toBinaryString(input3));
System.out.println(String.valueOf(input3));

will give an output:
1110
14

Long input3 = input1 + input2;
System.out.println(Long.toBinaryString(input3));
System.out.println(String.valueOf(input3));

will give an output:
10010
18
Commented:
the above code is wrong
>example:
>Long input3 = input1 & input2;
>System.out.println(Long.toBinaryString(input3));
>System.out.println(String.valueOf(input3));
>will give an output:
>1110
>14

the correct one is:
example:
Long input3 = input1 | input2;
System.out.println(Long.toBinaryString(input3));
System.out.println(String.valueOf(input3));

will give an output:
1110
14

example:
Long input3 = input1 & input2;
System.out.println(Long.toBinaryString(input3));
System.out.println(String.valueOf(input3));

will give an output:
0100
4

sorry, my mistake.

here is a static methods which can help you to set a bit and clear a bit
// helper variables
private static final long[] location;
static
{
location = new long[64];
for (int i = 0; i < 64; i++)
location[i] = 1L << i;
}

//static methods for convinience
public static long setBit(Long l, int loc)
{
return l | location[loc];
}

public static long clearBit(long l, int loc)
{
return l & ~location[loc];
}

public static boolean isBitSet(long l, int loc)
{
return (l & location[loc]) != 0;
}
Author Commented:
thanx 4 all ur input so far, but
Thing is, the input will be entered as decimal, and i will program to convert it to binary by using:
Integer.toBinaryString

but this makes it a STRING, and so i dont know how to convert to a list of ints, which i could then use as a array of ints...

i need to be able to manipulate it as ints,(and it must be done bitwise, since i need to use the bits later individually).

Commented:
The following method will convert an integer into an array of integers with 0s and 1s:

public static int[] toBitArray(int val) {
int []intBitArray = new int[32];

for (int i=0; i<intBitArray.length; i++) {
intBitArray[intBitArray.length-1 - i] = (((val << i) & bitmask) == 0?0:1);
}
return intBitArray;
}
Author Commented:
To: objects

How would i go about using the BitSet??  ive never used it before.
Author Commented:
does anybody know to use BitSet??
Commented:
As far as your description goes, you would not benefit much from using the BitSet class unless you extend it and add the methods you need. If you know how sets work and how bits work, reading the Javadocs for BitSet should be enough.
Java DeveloperCommented:
String s = Integer.toBinaryString(i);
char[] chars = s.toCharArray();
BitSet s = new BitSet(chars.length);
for (int i=0; i<chars.length; i++)
{
s.set(i, chars[i]=='1');
}
Author Commented:
ifi have 2, 8bit binary numbers, how do i separate these bits? in order to add. i need to show the carry as well as the sum. thereafter i need to regroup the numbers to show the sum.

also, would list and iterators help??
Commented:
This use the same algorithm I've provided you above

int bits;

this.bits = bits;

int binNum[] = toBitsArray( num );
int binResult = new int[bits+1];

print(binNum); System.out.println("  +");

int carry = 0;
for(int i=bits-1; i<=0; i--) {
int num = binNum[i] + binAdder[i] + carry;
binResult[i+1] = num % 2;
System.out.println(binNum[i]+" + "+binAdder[i]+" + "+carry+" = "+binResult[i+1]+" carry = "+(num>>1));
carry = num >> 1;
}
binResult[0] = carry;

System.out.println("------------");
println(binResult);
}

private void print(int[] array) {
for(int i=0; i<array.length; i++)  System.out.print(array[i]);
}

private void println(int[] array) {
for(int i=0; i<array.length; i++)  System.out.print(array[i]);
System.out.println();
}

private int[] toBitsArray(int no) {
StringBuffer n = new StringBuffer(Integer.toBinaryString( no ));
if(n.length() < bits) {
int remain = bits - n.length();
for(int i=0; i<remain; i++) n.insert(0, '0'); // pad left by '0'
} else {
int len = n.length();
n = n.substring(len-bits, len);
}
}

private int[] toIntArray(String binNo) {
int bin[] = new int[bits];
for(int i=0; i<bin.length; i++)
bin[i] = binNo.charAt(i) - '0';
return bin;
}

public static void main(String[] args) {
new BinaryAdding( 45, 45, 8 );
}

}

G noon
Author Commented:
gnoon:  i get so many errors when i try to use what u've given.
Commented:
Then try this code.....

public int[] convertString2intArray(String x1bin)
{
//each number has 8bit else i fill up with zeros in the font
for (int i = 7;i >-1 ;i--)
{
if (i < x1bin.length)
{
x1array[i] = 0;
}
else
{
x1array[i] = x1bin.charAt(i);
}
return x1array;
}
}

public int[] addIntArrays(int[] no1, int[] no2)
{
int [] result = new int[8];
for (int k = 0; k < 8; k++)
{
}
return result;
}
{
if ((first == 0) && (sec == 0)) return 0;
if ((first == 0) && (sec == 1)) return 1;
if ((first == 1) && (sec == 0)) return 1;
if ((first == 1) && (sec == 1)) return 0;
}
public static void main (String [] args)
{
String numberOne = args[0];
String numberTwo = args[1];
int no1 = convertString2intArray(args[0]);
int no2 = convertString2intArray(args[1]);
System.out.println(numberOne +" + "+numberTwo+" = " +sum);
}

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Author Commented:
To: objects or anyone else!!

URGENT !!!

after converting a binary string to an int, how do i make it an 8 bit integer, so that there are always 8 bits

i.e. 5 in binary is 101
but i want it to give me 00000101, as an 8 bit integer!!

very URGENT !!
Commented:
copy my code and it will work!!!

because that is what i am doing in method convertString2intArray()

!!!!

I wrote 30 lines of code witch do everything you want with even a main method and you dont even read it....

be ashamed...

Java DeveloperCommented:
And the code I posted will also achieve it, withthe minor modification that you just need to declare the BitSet to have 8 bits.

String s = Integer.toBinaryString(i);
char[] chars = s.toCharArray();
BitSet s = new BitSet(8);
for (int i=0; i<chars.length; i++)
{
s.set(i+(8-chars.length), chars[i]=='1');
}
Commented:
Sorry for the error code, I just wrote it on the board and didn't test it. I've fixed it now here.

int bits;

this.bits = bits;

int binNum[] = toBitsArray( num );
int binResult[] = new int[bits+1];

print(binNum); System.out.println( " ("+toInt(binNum)+")" ); System.out.println("  +");

int carry = 0;
for(int i=bits-1; i>=0; i--) {
int n = binNum[i] + binAdder[i] + carry;
binResult[i+1] = n % 2;
System.out.println(binNum[i]+" + "+binAdder[i]+" + "+carry+" = "+binResult[i+1]+" carry = "+(n>>1));
carry = n >> 1;
}
binResult[0] = carry;

System.out.println("\n------------");
print(binResult); System.out.println( " ("+toInt(binResult)+")" );
}

private void print(int[] array) {
for(int i=0; i<array.length; i++)  System.out.print(array[i]);
}

private void println(int[] array) {
for(int i=0; i<array.length; i++)  System.out.print(array[i]);
System.out.println();
}

private int[] toBitsArray(int no) {
StringBuffer n = new StringBuffer(Integer.toBinaryString( no ));
if(n.length() < bits) {
int remain = bits - n.length();
for(int i=0; i<remain; i++) n.insert(0, '0'); // pad left by '0'
} else {
int len = n.length();
n = new StringBuffer(n.substring(len-bits, len));
}
}

private int[] toIntArray(String binNo) {
int bin[] = new int[bits];
for(int i=0; i<bin.length; i++)
bin[i] = binNo.charAt(i) - '0';
return bin;
}

private int toInt(int[] bin) {
int result = 0;
for(int i=bin.length-1; i>=0; i--) {
if(bin[i] == 1)
}
return result;
}

public static void main(String[] args) {
new BinaryAdding( 45, 45, 8 );
}

}
Java DeveloperCommented:
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.