對於二進位制的字串進行二進位制整數轉換,並進行二進位制輸出,前面補0
阿新 • • 發佈:2019-01-01
package com.cn; public class TestT { public static char zero = "0".charAt(0); public static void main(String []args){ String x = "00000001"; String y = "00100001"; System.out.println(x+" + "+y+" = "+left(Long.toBinaryString(toLong(x)+toLong(y)),8)); } public static long toLong(String s){ long num = s.charAt(s.length()-1)-zero; for(int i=s.length()-1;i>0;i--){ num += Integer.valueOf(s.charAt(i)-zero)*(2<<(s.length()-2-i)); } return num; } public static String left(String s,int pos){ StringBuffer sb = new StringBuffer(); if(s.length()<pos){ for(int i=0;i<pos-s.length();i++){ sb.append("0"); } } return sb.toString()+s; } }