Here you can find the source of binaryToInt(String binaryValue, boolean signIncluded)
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. |
public static int binaryToInt(String binaryValue, boolean signIncluded)
//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; } }