Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 204
  • Last Modified:

converting a string binary to an int

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
imrama
Asked:
imrama
  • 21
  • 11
  • 10
1 Solution
 
CEHJCommented:
int i = Integer.parseInt(binary, 16);
0
 
CEHJCommented:
Not sure what this is?

>>bit = bin.readBit();
0
 
imramaAuthor Commented:
thanks! will close this if you can give me the answer to the other part too!!
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
imramaAuthor Commented:
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
 
imramaAuthor Commented:
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
 
objectsCommented:
> int i = Integer.parseInt(binary, 16);

Don't you mean:

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

0
 
CEHJCommented:
>>Don't you mean...


Yes!

What's this?

>>BitInputStream

?

0
 
CEHJCommented:
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
 
imramaAuthor Commented:
ya BitInputStream is a file that reads one bit in at a time from a file
0
 
CEHJCommented:
Line breaks or not?
0
 
objectsCommented:
> while (in.read() != -1)

The above reads a byte off the stream which you ignore.
0
 
imramaAuthor Commented:
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
 
CEHJCommented:
So you have a file something like this?

11110000
10010101
10000101
01010101

0
 
objectsCommented:
use something like:

while (bit = bin.readBit())
{
 ...
0
 
imramaAuthor Commented:
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
 
imramaAuthor Commented:
bit is an int though so i cant put that in there ill get an incompatable types error
0
 
CEHJCommented:
Are you able to open the file you're using in a text editor?
0
 
imramaAuthor Commented:
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
 
CEHJCommented:
AND there are line breaks?
0
 
objectsCommented:
> 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
 
imramaAuthor Commented:
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
 
objectsCommented:
        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
 
imramaAuthor Commented:
ya readBit returns an int

so int bit = readBit()

its what i posted earlier bit was declared as an int
0
 
imramaAuthor Commented:
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
 
objectsCommented:
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
 
objectsCommented:
while (null!=(codeword = reader.readLine()))
{
   System.out.println(codeword);
   arrays[i++] = codeword;
}
0
 
imramaAuthor Commented:
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
 
imramaAuthor Commented:
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
 
CEHJCommented:
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
 
objectsCommented:
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
 
imramaAuthor Commented:
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
 
imramaAuthor Commented:
objects bit is an int and you cant do while(bit = bin.readBit()) i tried that and it gives in compatable type error.
0
 
imramaAuthor Commented:
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
 
CEHJCommented:
>>note the file is a file of bits

There's no such thing really. The atomic unit is the byte
0
 
objectsCommented:
Woops my mistake :)  


Instead use:

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

0
 
imramaAuthor Commented:
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
 
imramaAuthor Commented:
bte its related to this too ;)
0
 
objectsCommented:
Depends what the next one is :)
0
 
imramaAuthor Commented:
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
 
imramaAuthor Commented:
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
 
imramaAuthor Commented:
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
 
objectsCommented:
Thanks for the points :-)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 21
  • 11
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now