How to convert a Binary String to a base 10 integer in Java

前端 未结 9 1331
野性不改
野性不改 2020-11-27 14:30

I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:

bi         


        
9条回答
  •  失恋的感觉
    2020-11-27 15:27

    int foo = Integer.parseInt("1001", 2);
    

    works just fine if you are dealing with positive numbers but if you need to deal with signed numbers you may need to sign extend your string then convert to an Int

    public class bit_fun {
        public static void main(String[] args) {
            int x= (int)Long.parseLong("FFFFFFFF", 16);
            System.out.println("x =" +x);       
    
            System.out.println(signExtend("1"));
            x= (int)Long.parseLong(signExtend("1"), 2);
            System.out.println("x =" +x);
    
            System.out.println(signExtend("0"));
            x= (int)Long.parseLong(signExtend("0"), 2);
            System.out.println("x =" +x);
    
            System.out.println(signExtend("1000"));
            x= (int)Long.parseLong(signExtend("1000"), 2);
            System.out.println("x =" +x);
    
            System.out.println(signExtend("01000"));
            x= (int)Long.parseLong(signExtend("01000"), 2);
            System.out.println("x =" +x);
        }
    
        private static String signExtend(String str){
            //TODO add bounds checking
            int n=32-str.length();
            char[] sign_ext = new char[n];
            Arrays.fill(sign_ext, str.charAt(0));
    
            return new String(sign_ext)+str;
        }
    }
    
    output:
    x =-1
    11111111111111111111111111111111
    x =-1
    00000000000000000000000000000000
    x =0
    11111111111111111111111111111000
    x =-8
    00000000000000000000000000001000
    x =8 
    

    I hope that helps!

提交回复
热议问题