Solved

urgent: reading binary numbers bit by bit

Posted on 2004-04-28
21
223 Views
Last Modified: 2010-03-31
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.

please help.
0
Comment
Question by:Faikad
  • 6
  • 4
  • 3
  • +3
21 Comments
 
LVL 6

Expert Comment

by:mightyone
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

by:Tommy Braas
ID: 10942137
What is the size of the binary numbers? 16bits? 32bits?
0
 
LVL 92

Expert Comment

by:objects
ID: 10944134
BitSet class may help you.
0
 
LVL 16

Expert Comment

by:gnoon
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

by:miracle_iu
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

by:miracle_iu
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

by:Faikad
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).

im getting very frustrated with all this, please help!!
0
 
LVL 14

Expert Comment

by:Tommy Braas
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

by:Faikad
ID: 10981945
To: objects

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

Author Comment

by:Faikad
ID: 10982083
does anybody know to use BitSet??
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 14

Expert Comment

by:Tommy Braas
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

by:objects
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

by:Faikad
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

by:gnoon
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 binAdder[] = toBitsArray( adder );
      int binResult = new int[bits+1];

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

      // adding
      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);
    }
    return toIntArray( n.toString() );
  }

  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 );
  }

}

This'll help you got solution.
G noon
0
 

Author Comment

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

Accepted Solution

by:
mightyone earned 125 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++)
   {
      result[k] = binAdd(no1[i],no2[i]);
   }
   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

by:Faikad
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

by:mightyone
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

by:objects
objects earned 125 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

by:gnoon
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 binAdder[] = toBitsArray( adder );
      int binResult[] = new int[bits+1];

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

      // adding
      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));
    }
    return toIntArray( n.toString() );
  }

  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

by:objects
ID: 11374821
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
The viewer will learn how to implement Singleton Design Pattern in Java.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now