"java program that converts binary numbers to decimal numbers. the input is a string of zeros and ones" Code Answer

1

do this only if your decimal value is at most 2147483647 or the maximum value an int can be in java. if you don't know, just check the length of your string. if it's less than or equal to 32 i.e. 4 bytes, then you can use parseint.:

int decimalvalue = integer.parseint(s, 2);

refer here for more info on the integer.parseint();

but if it's more, you can use your code. i modified your loop which is where your problem was:

 string s = "1001010101011010111001011101010101010101";
 long result = 0;
 for(int i = 0; i < s.length(); i++){
    result = (long) (result + (s.charat(i)-'0' )* math.pow(2, s.length()-i-1));
  }
    system.out.println(result);
By mroWsymaS on October 3 2022

Answers related to “java program that converts binary numbers to decimal numbers. the input is a string of zeros and ones”

Only authorized users can answer the Search term. Please sign in first, or register a free account.