【问题标题】:Java code or lib to decode a binary-coded decimal (BCD) from a String用于从字符串解码二进制编码的十进制 (BCD) 的 Java 代码或库
【发布时间】:2010-10-03 01:03:18
【问题描述】:

我有一个由 1 ('\u0031') 和 0's('\u0030') 组成的字符串,代表 BCD 值。

具体来说,字符串是 112 个字符,分别是 1 和 0,我需要一次提取 8 或 16 个字符,并将它们从 BCD 解码为十进制。

想法?包裹?库?代码?欢迎大家。

【问题讨论】:

    标签: java binary decimal decode bcd


    【解决方案1】:

    一次提取 4 个字符并使用 Integer.parseInt(string, 2) 应该给出每个数字。把你认为合适的数字组合起来。

    【讨论】:

      【解决方案2】:

      我认为你错过了所有的乐趣:

      这是 Pete Kirkham 建议的基本实现。

      花了大约 5 分钟。

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

      【讨论】:

        猜你喜欢
        • 2012-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-03
        • 1970-01-01
        • 2015-01-25
        相关资源
        最近更新 更多