Java Binary to Int binaryToInt(String binaryValue, boolean signIncluded)

Here you can find the source of binaryToInt(String binaryValue, boolean signIncluded)

Description

This method converts String that contains a binary to int.

License

LGPL

Parameter

Parameter Description
binaryValue String representing the binary, if other than {0,1} then null.
signIncluded Boolean value telling whether 11 is -1 or 3 i.e. will the leading one be interpreted as sign-bit.

Return

Int value of a Binary.

Declaration

public static int binaryToInt(String binaryValue, boolean signIncluded) 

Method Source Code

//package com.java2s;
// This software is released under GNU Lesser General Public License 2.1.

public class Main {
    /**//from ww w.  jav a2 s.  c  o  m
     * This method converts String that contains a binary to int. binaryToInt("01") --> 1
     *
     * @param binaryValue  String representing the binary, if other than {0,1} then null.
     * @param signIncluded Boolean value telling whether 11 is -1 or 3 i.e. will the leading
     *                     one be interpreted as sign-bit.
     * @return Int value of a Binary.
     */
    public static int binaryToInt(String binaryValue, boolean signIncluded) {
        /*  returns 0 when error! exception perhaps? */
        boolean isNegative = false;
        int value = 0;

        if (signIncluded) {
            if (binaryValue.charAt(0) == '1') {
                isNegative = true;
                binaryValue = binaryValue.replace('1', '2');
                binaryValue = binaryValue.replace('0', '1');
                binaryValue = binaryValue.replace('2', '0');
            }
        }

        for (int i = 0; i < binaryValue.length(); ++i) {
            if (binaryValue.charAt(binaryValue.length() - 1 - i) == '1') {
                value = value + (int) Math.pow(2.0, i * 1.0);
            } else {
                if (binaryValue.charAt(binaryValue.length() - 1 - i) != '0') {
                    return 0;
                }
            }
        }

        if (isNegative) {
            value = (value + 1) * -1;
        }
        return value;
    }
}

Related

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