[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
Solved

urgent: reading binary numbers bit by bit

Posted on 2004-04-28
Medium Priority
248 Views
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.

0
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• Learn & ask questions
• 6
• 4
• 3
• +3

LVL 6

Expert Comment

ID: 10942034
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

...
0

LVL 14

Expert Comment

ID: 10942137
What is the size of the binary numbers? 16bits? 32bits?
0

LVL 92

Expert Comment

ID: 10944134
0

LVL 16

Expert Comment

ID: 10947084
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 adder = adderBits[i] - zero; // if i = 6, adder = 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
0

Expert Comment

ID: 10947191
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
0

Expert Comment

ID: 10947358
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;
}
0

Author Comment

ID: 10981687
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).

0

LVL 14

Expert Comment

ID: 10981892
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];
int bitmask = 1<<31;

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

Author Comment

ID: 10981945
To: objects

How would i go about using the BitSet??  ive never used it before.
0

Author Comment

ID: 10982083
does anybody know to use BitSet??
0

LVL 14

Expert Comment

ID: 10982273
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.
0

LVL 92

Expert Comment

ID: 10982341
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');
}
0

Author Comment

ID: 10986904
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??
0

LVL 16

Expert Comment

ID: 10993632
This use the same algorithm I've provided you above

public class BinaryAdding {

int bits;

public BinaryAdding(int num, int adder, 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
0

Author Comment

ID: 10994654
gnoon:  i get so many errors when i try to use what u've given.
0

LVL 6

Accepted Solution

mightyone earned 375 total points
ID: 10996691
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;
}
public int binAdd(int first,int sec)
{
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]);
int sum = addIntArrays(no1, no2);
System.out.println(numberOne +" + "+numberTwo+" = " +sum);
}
0

Author Comment

ID: 10998436
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 !!
0

LVL 6

Expert Comment

ID: 10999375
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...

0

LVL 92

Assisted Solution

objects earned 375 total points
ID: 11000431
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');
}
0

LVL 16

Expert Comment

ID: 11001320
Sorry for the error code, I just wrote it on the board and didn't test it. I've fixed it now here.

public class BinaryAdding {

int bits;

public BinaryAdding(int num, int adder, 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;
int mask = bin.length-1;
for(int i=bin.length-1; i>=0; i--) {
if(bin[i] == 1)
result += 1 << (mask-i);
}
return result;
}

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

}
0

LVL 92

Expert Comment

ID: 11374821
0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how â€¦
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importingâ€¦
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month13 days, 3 hours left to enroll

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.