Reputation: 679
How to convert a binary String such as
String c = "110010"; // as binary
to the value in decimal in Java? (expected result in the example is 50)
Upvotes: 42
Views: 170542
Reputation: 2807
let's say 23456789
it has a binary string of 1011001011110110000010101
easiest way is to put all copies of the base needed on the left, which should always be string length - 1
(assuming not leading edge zeros), put and all the coefficients on the right :
echo '1011001011110110000010101' |
mawk 'function __(_) {
print; gsub(/./, "2*(", _)
return substr(_, 4)
}
$!_ = __($_) $!_' FS= OFS=')+' | gtee >( gcat -b | lgp3 >&2; ) | bc
23456789
1011001011110110000010101
2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(
+1)+0)+1)+1)+0)+0)+1)+0)+1)+1)+1)+1)+0)+1)+1)+0)+0)+0)+0)+0)+1)+0)+1)+0)+1
2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(
1) )+1)+1) ) )+1) )+1)+1)+1)+1) )+1)+1) ) ) ) ) )+1) )+1) )+1
2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(
2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(2*(1) )+1)+1)))+1))+1)+1)+1)+1)
)+1)+1) ))) ))+1) )+1) )+1
versus the standard form, which is succinct only for base-2, and more helpful for polynomials than for bit-string/vector conversion :
2^24 + 2^22 + 2^21 + 2^18 + 2^16 + 2^15 + 2^14 + 2^13 + 2^11 + 2^10 + 2^4 + 2^2
1*2^24 + 0*2^23 + 1*2^22 + 1*2^21 + 0*2^20 + 0*2^19 +
1*2^18 + 0*2^17 + 1*2^16 + 1*2^15 + 1*2^14 + 1*2^13 +
0*2^12 + 1*2^11 + 1*2^10 + 0*2^ 9 + 0*2^ 8 + 0*2^ 7 +
0*2^ 6 + 0*2^ 5 + 1*2^ 4 + 0*2^ 3 + 1*2^ 2 + 0*2 + 1
Digits are always kept adjacent to one another, in big-endian notation, without the base and exponent getting in the way
It completely eliminated the power operator ^
from the chain of operations by using nested layers of the base supporting one another instead.
Count up # of 2*
s (i.e. (1 << 1)
) to get floor of log2(x)
Similarly, count up # of 10*
s (i.e. ((1 << 3) + (1 << 1)
) in the decimal version to get floor of log10(x)
For each of the 1
bits, the power of 2 exponent associated with it would be just # of closing parenthesis )
to its right
The decimal equivalent of this structure is shown below. If anything, the condensed gapless form of the notation increases readability due to close proximity of digits with one another.
10*(10*(10*(10*(10*(10*(10*(
2)+ 3)+ 4)+ 5)+ 6)+ 7)+ 8)+ 9
10*(10*(10*(10*(10*(10*(10*(2)+3)+4)+5)+6)+7)+8)+9
But instead of using the minimum of 7 copies of 10
and 8 coefficient digits for a total of 15 numbers, the standard form needs 21 numbers for including superfluous exponents that could be easily derived just by counting layers in nested form.
2*10^7 + 3*10^6 + 4*10^5 + 5*10^4 +
6*10^3 + 7*10^2 + 8*10 + 9
2*10^7 + 3*10^6 + 4*10^5 + 5*10^4 + 6*10^3 + 7*10^2 + 8*10 + 9
The clutter in its gapless form…
2*10^7+3*10^6+4*10^5+5*10^4+6*10^3+7*10^2+8*10+9
Once you see numbers in any base in this nested form instead of standard notation, then base-conversion becomes a trivial exercise of nothing more than peeling back the nested layers.
Upvotes: 0
Reputation: 4776
According to this : we can write this help function :
public static int convertBinaryToDecimal(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
int value = Character.getNumericValue(str.charAt(i));
result = result * 2 + value;
}
return result;
}
Upvotes: 0
Reputation: 852
int base2(String bits) {
int ans = 0;
for (int i = bits.length() - 1, f = 1; i >= 0; i--) {
ans += f * (bits.charAt(i) - '0');
f <<= 1;
}
return ans;
}
Upvotes: -1
Reputation: 126
test this, you'll find out that there is a line in the code which contains Scan.S() .This is used only for stocking data (String). So just try this:
PS:Don't forget to save the file as bindec
import java.io.*;
class Scan
{
public static String S()
{
String x;
char c;
boolean erreur;
do
{
x = "";
erreur = false;
try
{
while((c = (char)System.in.read()) != '\n')
{
if (c != '\r')
{
x += c;
}
}
}
catch(IOException e)
{
System.out.print(" > enter String : ");
erreur = true;
}
} while(erreur);
return x;
}
public class bindec{
public static void main (String[] args) {
int b=0;
String a;
System.out.println("bin: ");
a = Lire.S();
int j=a.length()-1;
for(int i=0;i<a.length() ;i++ ){
if(a.charAt(i)=='1'){
b += Math.pow(2,j);
}
if(a.charAt(i)=='0'){
b+=0;
}
j=j-1;
}
System.out.println("dec: "+b);
}
}
Upvotes: 0
Reputation: 1
import java.util.*;
public class BinaryToDecimal
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the binary number");
double s=sc.nextDouble();
int c=0;
long s1=0;
while(s>0)
{
s1=s1+(long)(Math.pow(2,c)*(long)(s%10));
s=(long)s/10;
c++;
}
System.out.println("The respective decimal number is : "+s1);
}
}
Upvotes: -1
Reputation: 21
Have to think about the decimal precision, so you must to limit the bitstring length. Anyway, using BigDecimal is a good choice.
public BigDecimal bitStringToBigDecimal(String bitStr){
BigDecimal sum = new BigDecimal("0");
BigDecimal base = new BigDecimal(2);
BigDecimal temp;
for(int i=0;i<bitStr.length();i++){
if(bitStr.charAt(i)== '1'){
int exponent= bitStr.length()-1-i;
temp=base.pow(exponent);
sum=sum.add(temp);
}
}
return sum;
}
Upvotes: 2
Reputation: 1
public static void main(String[] args) {
java.util.Scanner scan = new java.util.Scanner(System.in);
long decimalValue = 0;
System.out.println("Please enter a positive binary number.(Only 1s and 0s)");
//This reads the input as a String and splits each symbol into
//array list
String element = scan.nextLine();
String[] array = element.split("");
//This assigns the length to integer arrys based on actual number of
//symbols entered
int[] numberSplit = new int[array.length];
int position = array.length - 1; //set beginning position to the end of array
//This turns String array into Integer array
for (int i = 0; i < array.length; i++) {
numberSplit[i] = Integer.parseInt(array[i]);
}
//This loop goes from last to first position of an array making
//calculation where power of 2 is the current loop instance number
for (int i = 0; i < array.length; i++) {
if (numberSplit[position] == 1) {
decimalValue = decimalValue + (long) Math.pow(2, i);
}
position--;
}
System.out.println(decimalValue);
main(null);
}
Upvotes: -1
Reputation: 1679
private static int convertBinaryToDecimal(String strOfBinary){
int flag = 1, binary=0;
char binaryOne = '1';
char[] charArray = strOfBinary.toCharArray();
for(int i=charArray.length-1;i>=0;i--){
if(charArray[i] == binaryOne){
binary+=flag;
}
flag*=2;
}
return binary;
}
Upvotes: -1
Reputation: 9
Test it
import java.util.Scanner;
public class BinaryToDecimal{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int binaryNumber = 0;
int counter = 0;
int number = 0;
System.out.print("Input binary number: ");
binaryNumber = input.nextInt();
//it's going to stop when the binaryNumber/10 is less than 0
//example:
//binaryNumber = 11/10. The result value is 1 when you do the next
//operation 1/10 . The result value is 0
while(binaryNumber != 0)
{
//Obtaining the remainder of the division and multiplying it
//with the number raised to two
//adding it up with the previous result
number += ((binaryNumber % 10)) * Math.pow(2,counter);
binaryNumber /= 10; //removing one digit from the binary number
//Increasing counter 2^0, 2^1, 2^2, 2^3.....
counter++;
}
System.out.println("Decimal number : " + number);
}
}
Upvotes: -1
Reputation: 51
public static Long binToDec(String bin) {
long dec = 0L;
long pow = 1L;
for (int i = (bin.length() - 1); i >= 0; i--) {
char c = bin.charAt(i);
dec = dec + (Long.parseLong(c + "") * pow);
pow = pow * 2;
}
return dec;
}
or
long num = Long.parseLong("101110111",2);
Upvotes: 2
Reputation: 7
public static void convertStringToDecimal(String binary)
{
int decimal=0;
int power=0;
while(binary.length()>0)
{
int temp = Integer.parseInt(binary.charAt((binary.length())-1)+"");
decimal+=temp*Math.pow(2, power++);
binary=binary.substring(0,binary.length()-1);
}
System.out.println(decimal);
}
Upvotes: -1
Reputation: 181
public static int integerfrmbinary(String str){
double j=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)== '1'){
j=j+ Math.pow(2,str.length()-1-i);
}
}
return (int) j;
}
This piece of code I have written manually. You can also use parseInt as mentioned above . This function will give decimal value corresponding to the binary string :)
Upvotes: 18
Reputation: 47675
Use Integer.parseInt
(see javadoc), that converts your String
to int
using base two:
int decimalValue = Integer.parseInt(c, 2);
Upvotes: 102
Reputation: 19448
I think you are looking for Integer.parseInt. The second argument takes a radix, which in this case is 2.
Integer.parseInt(c, 2)
Upvotes: 13