Java code or lib to decode a binary-coded decimal (BCD) from a String

南楼画角 提交于 2019-12-13 13:18:21

问题


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? All is welcome.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/471253/java-code-or-lib-to-decode-a-binary-coded-decimal-bcd-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!