Java Binary to Int binaryToLong(String bin)

Here you can find the source of binaryToLong(String bin)

Description

A quick method to convert bin, a binary representation, to an integer number.

License

Open Source License

Parameter

Parameter Description
bin The number to convert

Declaration

public static long binaryToLong(String bin) 

Method Source Code

//package com.java2s;
/* This file is part of Math4J.
 * Math4J is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.//from  www. ja  v a 2s  .  c om
 *
 * Math4J is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Math4J; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 * 
 * Copyright 2005 Anthony Magee
 */

public class Main {
    /**
     * A quick method to convert <code>bin</code>, a binary representation,
     * to an integer number.
     * 
     * @param bin The number to convert
     */
    public static long binaryToLong(String bin) {
        /*
         * long returnVal = 0L; char[] binChars = bin.toCharArray();
         * 
         * if(binChars.length > 63) throw new IllegalArgumentException("Argument
         * cannot be more than 63 characters in length due to primitive memory
         * limits\r\nArgument length is " + binChars.length);
         * 
         * for(int i = 0; i < binChars.length; i++) { if(binChars[i] != '0' &&
         * binChars[i] != '1') throw new IllegalArgumentException("Argument is
         * not a binary representation. It contains values other than \'0\' and
         * \'1\'"); }
         * 
         * for(int i = 0; i < binChars.length; i++) { if(binChars[i] == '1')
         * returnVal += (long) Math.pow(2, binChars.length - 1 - i); }
         */

        boolean validBinary = true;
        char[] binArray = bin.toCharArray();
        for (int i = 0; validBinary && i < binArray.length; i++) {
            if (binArray[i] != '0' || binArray[i] != '1')
                validBinary = false;
        }
        if (validBinary)
            return Long.parseLong(bin, 2);
        else
            throw new ArithmeticException("Invalid string representation of a binary number: " + bin);
    }
}

Related

  1. bin2int(byte[] array, int offset)
  2. binaryToInt(String binary, int intlength)
  3. binaryToInt(String binaryValue, boolean signIncluded)
  4. binToDec(String str)
  5. boolean2integer(boolean b)
  6. boolean2integer(boolean b)