0

Very strange - Java - Convert decimal int to binary and sum the ones?

import java.util.Scanner; import java.util.Arrays; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int input = scanner.nextInt(); String result = toBinary(input); System.out.println(result); int num = 0; for (int i = 0; i < result.length(); i++){ char c = result.charAt(i); num += (int) c; } System.out.println(num); } public static String toBinary(int input){ String binary = ""; while (input > 0){ binary = (input % 2) + binary; input /= 2; } return binary; } } All I'm trying to do is sum the binary ones from an int, but for example, 15 goes to 1111, which goes to 196? Why?

3rd Sep 2021, 10:36 AM
Ethan
3 Answers
+ 2
Because of ASCII value. Binary of 15 is 1111 You store this result as String. Then you get characters in string("1111") one by one. You store this as character and convert to integer. So convert from String to integer it uses ASCII Value. ASCII value of 1 is 49 You did the same loop for 4 times. So "1"+"1"+"1"+"1"=49+49+49+49(ASCII value) So it gives to you 196 So use Integer.valueOf(result); It gives integer of string int number = Integer.valueOf(result); int sum=0; while (number > 0) { // Finding the remainder (Last Digit) int remainder = number % 10; // Printing the remainder/current last digit sum+=remainder; // Removing the last digit/current last digit number = number / 10; } System.out.println(sum);
3rd Sep 2021, 11:09 AM
Vadivelan
0
Perfect, thanks
3rd Sep 2021, 11:28 AM
Ethan