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

前端 未结 9 1373
野性不改
野性不改 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:21

    Fixed version of java's Integer.parseInt(text) to work with negative numbers:

    public static int parseInt(String binary) {
        if (binary.length() < Integer.SIZE) return Integer.parseInt(binary, 2);
    
        int result = 0;
        byte[] bytes = binary.getBytes();
    
        for (int i = 0; i < bytes.length; i++) {
            if (bytes[i] == 49) {
                result = result | (1 << (bytes.length - 1 - i));
            }
        }
    
        return result;
    }
    

提交回复
热议问题