?
Solved

converting a string binary to an int

Posted on 2003-03-24
42
Medium Priority
?
201 Views
Last Modified: 2010-03-31
lets say i have the string binary

String binary = 10010101;
and i want to get the decimal (integer) equivalent how is that done?

also im trying to read from a file using FileinputStream
and when i use
this code
while(in.read() != -1)
{
 
           bit = bin.readBit();
                    codeword = codeword + bit;
}

when i try to print out codeword later it just prints null why wont that read in the file??

Thanks for any help
0
Comment
Question by:imrama
[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
  • 21
  • 11
  • 10
42 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198078
int i = Integer.parseInt(binary, 16);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198088
Not sure what this is?

>>bit = bin.readBit();
0
 

Author Comment

by:imrama
ID: 8198089
thanks! will close this if you can give me the answer to the other part too!!
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 

Author Comment

by:imrama
ID: 8198096
ok ill post the whole code:

BitInputStream bin = new BitInputStream( in );
          String [] arrays = new String [100];
          boolean input = true;
          String codeword = new String();
          int i = 0;
          int j = 0;
          int bitcount = 0;
          int bit= 3;
          while (in.read() != -1)
          {
               if(bitcount != 7)
               {
                    bit = bin.readBit();
                    codeword = codeword + bit;
               }
                    bitcount++;
               if (bitcount == 7)
               {
                    arrays[i] = codeword;
                    i++;
                    System.out.println(i);
                    bitcount = 0;
                    codeword = "";
               }
               j++;
          }
0
 

Author Comment

by:imrama
ID: 8198101
then when i try to print out arrays like such:

     for ( i = 0;i < arrays.length ;i++ )
               {
                    System.out.println(arrays[i]);
                   
               }

i get
null
null
null

etc.
0
 
LVL 92

Expert Comment

by:objects
ID: 8198112
> int i = Integer.parseInt(binary, 16);

Don't you mean:

int i = Integer.parseInt(binary, 2);

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198132
>>Don't you mean...


Yes!

What's this?

>>BitInputStream

?

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198141
Do i take it you have a file of bit patterns? If so, can you tell me what the format is - i.e. are there any line breaks in there etc.?
0
 

Author Comment

by:imrama
ID: 8198166
ya BitInputStream is a file that reads one bit in at a time from a file
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198178
Line breaks or not?
0
 
LVL 92

Expert Comment

by:objects
ID: 8198192
> while (in.read() != -1)

The above reads a byte off the stream which you ignore.
0
 

Author Comment

by:imrama
ID: 8198209
oh ya.  

in.read will read a whole byte but im trying to read a byte the bit = bin.readBit reads one bit at a time but then i have already tried to read in a bit, i get ya now, what is the way around this?

Ya cehj it does include line breaks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198226
So you have a file something like this?

11110000
10010101
10000101
01010101

0
 
LVL 92

Expert Comment

by:objects
ID: 8198258
use something like:

while (bit = bin.readBit())
{
 ...
0
 

Author Comment

by:imrama
ID: 8198275
ya i have a file like that and here is the BitInputStream file:

 class BitInputStream
   {
     private InputStream in;
     private int buffer;
     private int nextBit = 8;
   
     public BitInputStream( InputStream in ) {
       this.in = in;
     }
   
     synchronized public int readBit() throws IOException {
       if (in == null)
         throw new IOException( "Already closed" );
   
       if (nextBit==8) {
         buffer = in.read();
   
         if (buffer==-1)
           throw new EOFException();
   
         nextBit = 0;
       }
   
       int bit = buffer & (1<<nextBit);
       nextBit++;
   
       bit = bit == 0 ? 0 : 1;
   
       return bit;
     }
   
     public void close() throws IOException {
       in.close();
       in = null;
     }
   }
0
 

Author Comment

by:imrama
ID: 8198286
bit is an int though so i cant put that in there ill get an incompatable types error
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198301
Are you able to open the file you're using in a text editor?
0
 

Author Comment

by:imrama
ID: 8198307
yes i am it comes out as all weird stuff, but i have a binary editor that shows the correct bits that should be in the file.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198328
AND there are line breaks?
0
 
LVL 92

Expert Comment

by:objects
ID: 8198337
> bit is an int though so i cant put that in there ill get an incompatable types error

What do u mean?
readBit() returns an int.
0
 

Author Comment

by:imrama
ID: 8198348
i can post the whole code if you want?? yes there are line breaks because i am using ascii characters an line break is number 10 in ascii.  will i post the whole code
0
 
LVL 92

Accepted Solution

by:
objects earned 105 total points
ID: 8198352
        while (bit = bin.readBit())
         {
              if(bitcount != 7)
              {
                   codeword = codeword + bit;
              }
                   bitcount++;
              if (bitcount == 7)
              {
                   arrays[i] = codeword;
                   i++;
                   System.out.println(i);
                   bitcount = 0;
                   codeword = "";
              }
              j++;
         }
0
 

Author Comment

by:imrama
ID: 8198360
ya readBit returns an int

so int bit = readBit()

its what i posted earlier bit was declared as an int
0
 

Author Comment

by:imrama
ID: 8198369
this is related to my previous question that i asked about lzw i never got a proper answer but im asking this now, so I will award the points of that question to either of you as well ( 75 points )  - as you answered a part of it already - if you can help me with this.
0
 
LVL 92

Expert Comment

by:objects
ID: 8198376
That is what you are trying to do, but it aint going to work if your file is a text file as stated above.
You should instead be simply using a BufferedReader to read each line in the file directly.
0
 
LVL 92

Expert Comment

by:objects
ID: 8198392
while (null!=(codeword = reader.readLine()))
{
   System.out.println(codeword);
   arrays[i++] = codeword;
}
0
 

Author Comment

by:imrama
ID: 8198434
SOrry I dont fully understand the last post here is the code:  I have one part of the program that writes codewords to a file and the other part that reads codewords from a file like this ( by the way this is only trial not finished):


        {
        Vector stringTable = new Vector();
          Vector codevec = new Vector();
      //   Vector stringTable = new Vector();
        initializeTable(stringTable);// add codeword for each alphabet character to dict
        int tableIndex = 3;
       
        //FileInputStream in = new FileInputStream(args[0]);
        System.out.println("\n\nDECOMPRESSING: ->>>");
           /*

          BitInputStream bin = new BitInputStream( in );
          String [] arrays = new String [50];
          boolean input = true;
          String codeword = new String();
          int i = 0;
          int j = 0;
          int bitcount = 0;
          int bit= 3;
          while (j < 100)
          {
               
               if(bitcount != 7)
               {
                    bit = bin.readBit();
                    codeword = codeword + bit;
               }
                    bitcount++;
               if (bitcount == 7)
               {
                    arrays[i] = codeword;
                    i++;
                    System.out.println(i);
                    bitcount = 0;
                    codeword = "";
               }
               j++;
          }
           
         
                           
               for ( i = 0;i < arrays.length ;i++ )
               {
                    System.out.println(arrays[i]);
                   
               }

               for ( i = 0;i < 10 ;i++ )
               {
                    codevec.addElement(Integer.parseInt(arrays[i], 2) + "");
                    System.out.println(codevec.get(i).toString());
                   
               }
               writecodetoFile(codevec);//this method writes to a file called "codes.txt"
               
               System.out.println(arrays.length);


and the other:

FileInputStream win = new FileInputStream("codes.txt");
           String P = (char)win.read() + ""; // if P = read-input-code; then
         int P_Index = Integer.parseInt(P);
         P_Index--;
         String Dict_P = stringTable.get(P_Index).toString();
         System.out.println("\nOutputting " + Dict_P); // output dict(P)

         int C1 = win.read();

          while(C1 != -1) // while C = read-input-code; do
        {
               String C =  (char)C1 + "";
               int C_Index = Integer.parseInt(C);
               C_Index--; // ->> 1

               P_Index = Integer.parseInt(P);
               P_Index--; // ->> 0
               Dict_P = stringTable.get(P_Index).toString(); // ->> a

               if(C_Index <  stringTable.size())// if C in dict; then
               {
                    String Dict_C = stringTable.get(C_Index).toString();
                    System.out.println("\nOutputting " + Dict_C); // output dict(C)
                    String newEntry = Dict_P + Dict_C.charAt(0);// add dict(P) + first-char(dict(C)) to dict
                    //newEntry = newEntry + "";
                    stringTable.addElement(newEntry);
                    System.out.println("Adding " + newEntry);
               }
               else// else
               {
                    String S = Dict_P + Dict_P.charAt(0); // S = dict(P) + first-char(dict(P))
                    System.out.println("\nOutputting " + S);  // output S
                    System.out.println("Adding " + S);  // output S
                    //S = S + "";
                    stringTable.addElement(S);// add S to dict

               }//  end if C in ...

               P = C;

               C1 = win.read();
          }
          win.close();
0
 

Author Comment

by:imrama
ID: 8198442
at the first part note that i am only reading in 10 codewords just as a trial to make sure im doing it correctly.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198460
If you have your codeword file in the format i gave above, then you can use the following:

public static String[] getCodewords(String fileName) {
    java.util.ArrayList codewords = new java.util.ArrayList();
    BufferedReader in = null;
    String codeword = null;
    try {
      in = new BufferedReader(new FileReader(fileName));
      while ((codeword = in.readLine()) != null) {
        codewords.add(codeword);
      }
      return (String[])codewords.toArray(new String[]{});
    }
    catch(IOException e){
      e.printStackTrace();
      return null;
    }
    finally {
      try { in.close(); } catch(IOException e) { e.printStackTrace(); }
    }
  }
0
 
LVL 92

Expert Comment

by:objects
ID: 8198472
The approach you take depends on the format of the file which you have not provided details of.

Something like the following should work if it is stored as binary data:

 
        while (bit = bin.readBit())
        {
             if(bitcount != 7)
             {
                  codeword = codeword + bit;
             }
                  bitcount++;
             if (bitcount == 7)
             {
                  arrays[i] = codeword;
                  i++;
                  System.out.println(i);
                  bitcount = 0;
                  codeword = "";
             }
             j++;
        }  

And if it is stored as text then the following should be used (where reader is of type BufferedReader);

while (null!=(codeword = reader.readLine()))
{
  System.out.println(codeword);
  arrays[i++] = codeword;
}


0
 

Author Comment

by:imrama
ID: 8198487
but im trying to read in bits that wont read in bits, note the file is a file of bits and i need to read each bit at a time.
0
 

Author Comment

by:imrama
ID: 8198494
objects bit is an int and you cant do while(bit = bin.readBit()) i tried that and it gives in compatable type error.
0
 

Author Comment

by:imrama
ID: 8198503
here is the contents of the file that im reading in:

Ñ°Íêéõ¢ü}w[ïç³õXT›OW‡ãî¸|‹öãÙx-,†‡©

sorry its late where i am!!!hehe i should have provided this earlier. please ask if there is anything else required
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8198510
>>note the file is a file of bits

There's no such thing really. The atomic unit is the byte
0
 
LVL 92

Expert Comment

by:objects
ID: 8198516
Woops my mistake :)  


Instead use:

try
{
   while (true)
   {
      bit = bin.readBit();
      ...
   }
}
catch (EOFException ex)
{
   System.out.println("done");
}

0
 

Author Comment

by:imrama
ID: 8198550
ya worked sweet, right ill up this to 65 and I really will close ti if ye can help with the next one, that fair enough ;) ???
0
 

Author Comment

by:imrama
ID: 8198555
bte its related to this too ;)
0
 
LVL 92

Expert Comment

by:objects
ID: 8198590
Depends what the next one is :)
0
 

Author Comment

by:imrama
ID: 8198663
hehe
well see ive drawn a blank, the following piece of code which i also posted earlier, takes in a codeword i.e an integer from a file lets say 12, that is the position in the dictionary that I the first letter is at, I have set the dictionary to start with the ascii characters from 0 to 127, so it will read the next dictionary entry everytime etc and add to it if its not already there, however this code only reads an integer that is less than 10 i.e lets say the codeword is like this

69
78
42

(all being dictionary entries)

but the following code will only recognise it as
6
9
7
8
4
2

so what I want is to know what i have to change as i just cant think what is wrong.

 String P = (char)win.read() + ""; // if P = read-input-code; then
        int P_Index = Integer.parseInt(P);
        P_Index--;
        String Dict_P = stringTable.get(P_Index).toString();
        System.out.println("\nOutputting " + Dict_P); // output dict(P)

        int C1 = win.read();

         while(C1 != -1) // while C = read-input-code; do
       {
              String C =  (char)C1 + "";
              int C_Index = Integer.parseInt(C);
              C_Index--; // ->> 1

              P_Index = Integer.parseInt(P);
              P_Index--; // ->> 0
              Dict_P = stringTable.get(P_Index).toString(); // ->> a

              if(C_Index <  stringTable.size())// if C in dict; then
              {
                   String Dict_C = stringTable.get(C_Index).toString();
                   System.out.println("\nOutputting " + Dict_C); // output dict(C)
                   String newEntry = Dict_P + Dict_C.charAt(0);// add dict(P) + first-char(dict(C)) to dict
                   //newEntry = newEntry + "";
                   stringTable.addElement(newEntry);
                   System.out.println("Adding " + newEntry);
              }
              else// else
              {
                   String S = Dict_P + Dict_P.charAt(0); // S = dict(P) + first-char(dict(P))
                   System.out.println("\nOutputting " + S);  // output S
                   System.out.println("Adding " + S);  // output S
                   //S = S + "";
                   stringTable.addElement(S);// add S to dict

              }//  end if C in ...

              P = C;

              C1 = win.read();
         }
         win.close();


if your willing to answer it ill up the points.

I know this is chancey the arm as they say but im in that state now where i need too ;)
0
 

Author Comment

by:imrama
ID: 8198689
here is the whole file ( with your changes ):

import java.io.*;
import java.util.*;
import java.util.Vector;

 
   import java.io.*;
   
   class BitInputStream
   {
     private InputStream in;
     private int buffer;
     private int nextBit = 8;
   
     public BitInputStream( InputStream in ) {
       this.in = in;
     }
   
     synchronized public int readBit() throws IOException {
       if (in == null)
         throw new IOException( "Already closed" );
   
       if (nextBit==8) {
         buffer = in.read();
   
         if (buffer==-1)
           throw new EOFException();
   
         nextBit = 0;
       }
   
       int bit = buffer & (1<<nextBit);
       nextBit++;
   
       bit = bit == 0 ? 0 : 1;
   
       return bit;
     }
   
     public void close() throws IOException {
       in.close();
       in = null;
     }
   }



public class LZWde
{
      

      public static void main (String[] args)
      {
         if (args.length < 1)
             {
              System.out.println ("Usage:  java LZWde <input file>");
              System.exit(0);
         }

            try
        {
        Vector stringTable = new Vector();
            Vector codevec = new Vector();
      //   Vector stringTable = new Vector();
        initializeTable(stringTable);// add codeword for each alphabet character to dict
        int tableIndex = 3;
       
       FileInputStream in = new FileInputStream(args[0]);
        System.out.println("\n\nDECOMPRESSING: ->>>");
             
            BitInputStream bin = new BitInputStream( in );
            Vector storebin = new Vector();
            boolean input = true;
            String codeword = new String();
            int i = 0;
            int j = 0;
            int bitcount = 0;
            int bit= 3;
            /*while (j < 100)
            {
                  
                  if(bitcount != 7)
                  {
                        bit = bin.readBit();
                        codeword = codeword + bit;
                  }
                        bitcount++;
                  if (bitcount == 7)
                  {
                        arrays[i] = codeword;
                        i++;
                        System.out.println(i);
                        bitcount = 0;
                        codeword = "";
                  }
                  j++;
            }*/
            try
            {
                  while (true)
                  {
                        if(bitcount != 7)
                  {
                        bit = bin.readBit();
                        codeword = codeword + bit;
                  }
                        bitcount++;
                  if (bitcount == 7)
                  {
                        storebin.addElement(codeword);
                        i++;
                        System.out.println(i);
                        bitcount = 0;
                        codeword = "";
                  }
                  j++;
                  }
            }

            catch (EOFException ex)
            {
                  System.out.println("done");
            }


             
            
                                
                  for ( i = 0;i < storebin.size() ;i++ )
                  {
                        System.out.println(storebin.get(i).toString());
                        
                  }

                  for ( i = 0;i < storebin.size()  ;i++ )
                  {
                        codevec.addElement(Integer.parseInt(storebin.get(i).toString(), 2) + "");
                        System.out.println(codevec.get(i).toString());
                        
                  }
                  writecodetoFile(codevec);
                  
                  System.out.println(storebin.size());
             FileInputStream win = new FileInputStream("codes.txt");
             String P = (char)win.read() + ""; // if P = read-input-code; then
         int P_Index = Integer.parseInt(P);
         P_Index--;
         String Dict_P = stringTable.get(P_Index).toString();
         System.out.println("\nOutputting " + Dict_P); // output dict(P)

         int C1 = win.read();

            while(C1 != -1) // while C = read-input-code; do
        {
                  String C =  (char)C1 + "";
                  int C_Index = Integer.parseInt(C);
                  C_Index--; // ->> 1

                  P_Index = Integer.parseInt(P);
                  P_Index--; // ->> 0
                  Dict_P = stringTable.get(P_Index).toString(); // ->> a

                  if(C_Index <  stringTable.size())// if C in dict; then
                  {
                        String Dict_C = stringTable.get(C_Index).toString();
                        System.out.println("\nOutputting " + Dict_C); // output dict(C)
                        String newEntry = Dict_P + Dict_C.charAt(0);// add dict(P) + first-char(dict(C)) to dict
                        //newEntry = newEntry + "";
                        stringTable.addElement(newEntry);
                        System.out.println("Adding " + newEntry);
                  }
                  else// else
                  {
                        String S = Dict_P + Dict_P.charAt(0); // S = dict(P) + first-char(dict(P))
                        System.out.println("\nOutputting " + S);  // output S
                        System.out.println("Adding " + S);  // output S
                        //S = S + "";
                        stringTable.addElement(S);// add S to dict

                  }//  end if C in ...

                  P = C;

                  C1 = win.read();
            }
            win.close();
                  
     
                  catch(Exception e)
                  {
                        System.out.println(e.getMessage());
                  }
            
                  
                                                                   
                                                                      
     }

     private static  void initializeTable(Vector stringTable)
       {
          stringTable.addElement("");
             
             for (int i = 0;i < 127;i++ )
             {
                  
                   String s = (char)i + "";
                   stringTable.addElement(s);
                   System.out.println(s);
             }
     }
       static private void writecodetoFile(Vector outputArray)
      {
       try{

        FileOutputStream integer = new
      FileOutputStream("codes.txt", true);
        PrintWriter integerWriter = new PrintWriter(integer);

        for(int i = 0; i < outputArray.size(); i++)
        {
         integerWriter.write(outputArray.get(i) + "\n");
        }

        integerWriter.close();
        integer.close();

       } catch (Exception e) {}
      }
}

0
 

Author Comment

by:imrama
ID: 8203007
I got it working, thanks for the helps objects and cehj seeing as I used objects code I will award the points to him. Thanks again.
0
 
LVL 92

Expert Comment

by:objects
ID: 8205847
Thanks for the points :-)
0

Featured Post

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

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

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…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month10 days, 10 hours left to enroll

764 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