views:

2069

answers:

4

I have a string consisting of 1's ('\u0031') and 0's('\u0030') that represents a BCD value.

Specifically, the string is 112 characters worth of 1's and 0's and I need to extract either 8 or 16 of these at a time and decode them from BCD to decimal.

Ideas? Packages? Libs? Code? Snooty remarks about my sheer fucking laziness? All is welcome.

Thanks TJ

+2  A: 

Extracting 4 characters at a time and use Integer.parseInt(string, 2) should give each digit. Combine the digits as you see fit.

Pete Kirkham
A: 

Yes you are lazy. You can write a robust BCD decoder with unit tests in an hour or two I think. Post it on Google code please.

St3fan
A: 

I think you're missing all the fun:

Here's a basic implementation of what Pete Kirkham suggested.

Took about 5 mins.

import java.util.List;
import java.util.ArrayList;

public class Binary { 

        public static void main( String [] args ) { 

            for ( int i : Binary.fromString("0000000100100011010001010110011110001001") ) {
                System.out.print( i );   
             }  
             System.out.println();
        }

        public static List<Integer> fromString( String binaryString ) { 

            List<Integer> list   = new ArrayList<Integer>();
            StringBuilder buffer = new StringBuilder();
            int count            = 0;


            for ( char c : binaryString.toCharArray() ) {
                buffer.append( c );
                count++;

                if ( count >= 4 ) { 
                    list.add( Integer.parseInt( buffer.toString(), 2 ) );
                    count = 0;
                    buffer.delete( 0 , 4 );
                }
            }

            return list;
       }
}
OscarRyz
A: 

dekoder BCD/decimal