Java Binary to Decimal toDecimal(String binary)

Here you can find the source of toDecimal(String binary)

Description

This will convert the given binary string to a decimal based integer

License

Apache License

Parameter

Parameter Description
binary the binary string to convert

Return

an equivalent base 10 number

Declaration

public static int toDecimal(String binary) 

Method Source Code

//package com.java2s;
/*/*w  ww.ja v  a  2  s .  com*/
 *
 *  * Copyright 2015 Skymind,Inc.
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *        http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

public class Main {
    /**
     * This will convert the given binary string to a decimal based
     * integer
     * @param binary the binary string to convert
     * @return an equivalent base 10 number
     */
    public static int toDecimal(String binary) {
        long num = Long.parseLong(binary);
        long rem;
        /* Use the remainder method to ensure validity */
        while (num > 0) {
            rem = num % 10;
            num = num / 10;
            if (rem != 0 && rem != 1) {
                System.out.println("This is not a binary number.");
                System.out.println("Please try once again.");
                return -1;
            }
        }
        return Integer.parseInt(binary, 2);
    }
}

Related

  1. bin2dec(String bin)
  2. bin2dec(String str)