How to convert from binary to decimal in java? - java

I am trying to write code in java that takes a binary string from the user, then using arrays(?), makes it a base 10 integer. My friend trying to help me wrote this, but there is no variable "c" and i do not have any idea what he tried to do.
//Binary Conversion
System.out.println("Enter a value in binary to convert to decimal");
int binary =
int decimalValue = Integer.parseInt(c, 2);
Before this, i already had skeleton code and a declared keyboard scanner, so I assume that
int binary
is followed by
kbReader.nextInt();
Any help?

You can read the input as String using scanner.next();
then use the Integer parse method as you said which will take the input
string and the wanted radix which is in this case =2

**//Conversion between Binary & Decimal**
public static void main(String args[]){
**//Binary to Decimal**
String BtD = "10001110";
if(isBinary(Integer.parseInt(BtD))){
System.out.println("Binary Value is ==>> "+Integer.parseInt(BtD));
System.out.println("Decimal Value is ==>> "+Integer.parseInt(BtD,2));
}else{
System.out.println("Not an binary no");
}
**//Decimal to Binary**
int DtB = 142;
System.out.println("Decimal Value is ==>> "+DtB);
System.out.println("Binary Value is ==>> "+Integer.toBinaryString(DtB));
}
**//To check entered value is binary or not**
public static boolean isBinary(int number){
boolean status = true;
while(true){
if(number == 0){
break;
}else{
int temp = number % 10;
if(temp > 1){
status = false;
break;
}
number = number /10;
}
}
return status;
}

Related

Binary to Decimal calculator InputMismatchException

My goal is to create a simple binary to decimal calculator. I try to go about this by first having the user input a string of the binary value they are trying to calculate and later use the length of this string to run a for loop (as seen in the code below). The calculator appears to work fine but fails when the user enters a binary number (of all 1's) longer than 20 digits. I receive a java.util.InputMismatchException error and I don't know how to fix it.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
long binaryNum = scan.nextLong();
System.out.println(binaryConverter(binaryNum));
scan.close();
}
public static long binaryConverter(long binaryNum) {
String binaryString = Long.toString(binaryNum);
long decimalValue = 0;
for(int i = 0; i < binaryString.length(); i++) {
if((binaryNum%10) == 0) {
binaryNum = binaryNum/10;
} else if((binaryNum%10) == 1) {
decimalValue += Math.pow(2, i);
binaryNum = binaryNum/10;
} else {
System.out.println("This isn't a binary number. Please try again.");
break;
}
}
return decimalValue;
}
}
The way you want to do this to use scanner.nextLong(2) where 2 is the radix. Then you will be reading in an actual binary number.
long number = scanner.nextLong(2);
System.out.println(number);
produces
144115188075855871
for input of
111111111111111111111111111111111111111111111111111111111
If I understood you correctly you always want to convert the binary input to a decimal value. A very simple solution would look like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
final String input = scan.next();
System.out.println(Integer.parseInt(input, 2));
scan.close();
}
If you are interested how it works under the hood, take a look at the java source for Integer.parseInt.

converting to decimal but without using integer.parseInt() method

So this is my first programming course and I have an assignment to convert a binary number entered by the user to a decimal. And my binary number should be stored in a a string.
And to check that all my digits are 1s and 0s I need to use a method to make sure it's valid and return true if the the number is correct and false otherwise.
So I did a search and saw that everyone was using the integer.parseInt(String , int radix) method to convert a binary string to int which worked completely fine, however, the only problem is we didn't take this with my professor so I'm not sure if it's OK and that maybe he wants another way to convert it?
So my question is: how can I write this code in another way that doesn't use this method?.
Here's my code:
import java.util.*;
import java.lang.*;
public class Assignment2
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int converttodecimal;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
converttodecimal = Integer.parseInt(st,2);// integer.parseInt(String , int radix);
System.out.println("the equivalent decimal value is: " +converttodecimal );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
}//end of class
This is the output:
enter a binary number to convert to decimal:
110101
the equivalent decimal value is: 53
Thank you in advance I already asked this question else where but I didn't get the answer I wanted.
UPDATE:
I wrote the program again based on your suggestions #akhil_mittal #fabian but if i want to write the converting method in the program itself (not calling the method) how can i do that ?
here's the code:
import java.util.*;
import java.lang.*;
public class Assignment2test
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int result;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
result = convertBinaryToDecimal(st);
System.out.println("the equivalent decimal value is: " + result );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
public static int convertBinaryToDecimal(String st){
double decimal =0;
for(int i=0;i<st.length();i++){
if(st.charAt(i)== '1'){
decimal = decimal + Math.pow(2,st.length()-1-i);
}
}
return (int) decimal;
}
}
//end of class
Do it manually, you can just multiply each digit for the corresponding power of two and sum the results.
Regarding the last part of your question, you can simply use java.lang.Math.pow(2,exponent), there is no specific operator for that if that was what you were wondering.
You can use the bit-shift operator to get powers of 2:
int pow2(int exponent) {
return 1 << exponent;
}
which should be more efficient than Math.pow.
But you could also calculate a binary number like this (example for 0b110101):
((((((1)*2+1)*2+0)*2+1)*2+0)*2+1)
i.e. by repeatedly multiplying by 2 and adding the next digit.
I have written two methods which use basic computation to convert binary to decimal, one takes long and other takes String. You can also use them to check the differences in implementation. The method is very simple and easy to understand.
public static int convertBinaryToDecimal(String binary){
double decimal =0;
for(int i=0;i<binary.length();i++){
if(binary.charAt(i)== '1'){
decimal = decimal + Math.pow(2,binary.length()-1-i);
}
}
return (int) decimal;
}
public static int convertBinaryToDecimal(long numberInBinary){
int decimal = 0;
int power = 0;
while(true){
if(numberInBinary == 0){
break;
} else {
long temp = numberInBinary%10;
decimal += temp*Math.pow(2, power);
numberInBinary = numberInBinary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
int binaryNumber = 110011;
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumber));
String binaryNumberInString = "110011";
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumberInString));
}
If you want to ensure that String only contains 0 and 1 then you can try yourself and let me know if you need any help.
Binary to decimal Conversion without using Integer.parseInt method
public class BinaryDecimal
{
public static int binaryToDecimal(int binary) {
int decimal = 0;
for (int power = 1; binary > 0; power *= 2, binary /= 10)
decimal += power * (binary % 10);
return decimal;
}
public static void main(String a[]) {
System.out.println("11 ===> " + binaryToDecimal(11));
//System.out.println("11 ===> " + binaryToDecimal(Integer.parseInt(a[0]))); //Input from command line
}
}

binary to base10 in java with main method and TWO classes/method (boolean and

I am a beginner programmer. This is what I have so far. The directions for the question are kind of difficult. Here is what I am trying to accomplish..
You will write a program that converts binary numbers to base 10 numbers. This program will ask the user to enter a binary number. You will have to verify that what is entered by the user only has 0s and 1s. In the case the user entered letters, you have to keep asking the user for another input. When the input is valid, you will convert the binary number to a base 10 number. Please use the Question1.java file provided in the A2.zip file.
Valid input - In order to check if the input is valid your program should call the CheckInputCorrect method, which takes a String as an input parameter and returns a boolean value. An input string is considered valid if it corresponds to a number in binary representation.
More specifically, in the CheckInputCorrect method, you should scan this string to make sure it only contains ‘0’ or ‘1’ characters. As soon as you find a character that is not ‘0’ or ‘1’, the method should returns false. If the method reaches the end of the input string (i.e. all characters are ‘0’ or ‘1’) the method should return true.
Converter - At this point we assume that the input string is valid (checked with the CheckInputCorrect method). To convert the input from binary to base 10, you must implement the BinaryToNumber method. The BinaryToNumber method should take as parameter a String and return an integer, which corresponds to converted value in base 10.
The binary conversion should work as follows. For each digit in the binary number, if the digit is ‘1’ you should add the corresponding decimal value ( 20 for the rightmost digit, 21 for the next digits to the left, 22 for the next one, and so on) to a variable that will hold the final result to be returned. This can be easily accomplished by using a loop.
1) Am I on the right path?
2) I don't exactly know what I am doing and need you to help me figure that out....
Update1:
When I run this vvvv: It says "Please enter a binary number for me to convert: and then a place for me to type in my answer but whatever i put it just returns another box for me to type in but stops and doesn't evaluated anything.
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
boolean BinaryNumber = false;
String inputString = "";
while (!BinaryNumber){
inputString = inputKeyboard.next();
BinaryNumber = CheckInputCorrect(inputString);
System.out.println("You have given me a " + BinaryNumber + "string of binary numbers.");
}
int finalNumber = BinaryToNumber(inputString);
System.out.println("Congratulations, your binary number is " + finalNumber + ".");
}
public static boolean CheckInputCorrect(String input)
{
for (int i = 0; i < input.length(); i++)
{
while (i < input.length());
if (input.charAt(i) != '0' && input.charAt(i) != '1')
{return false;}
i++;
}
return true;
}
public static int BinaryToNumber(String numberInput)
{
int total = 0;
for (int i = 0; i < numberInput.length(); i++){
if (numberInput.charAt(i)=='1')
{
total += (int)Math.pow(2,numberInput.length() - 1 - i);
}
}
return total;
}
}
Original:
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
int binarynumber;
int arraySize = {0,1};
int[] binaryinput = new int[arraySize];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a binary number");
binarynumber = in.nextInt();
if (binarynumber <0)
{
System.out.println("Error: Not a positive integer");
}
if (CheckInputCorrect) = true;
{
System.out.print(CheckInputCorrect);
}
public static boolean CheckInputCorrect(String input);
{
boolean b = true;
int x, y;
x = 0
y = 1
b = x || y
while (b >= 0 {
System.out.print("Please enter a binary number")
for (int i = 0; i < binarynumber.length; i++)
{
binaryinput[i] = in.nextInt();
if (binaryinput[i] = b.nextInt();
System.out.printl("Binary number is:" + binaryinput);
break outer;
if (binarynumber != b)
{
System.out.println("Error: Not a binary number")
}
return true;
}
}
public static int BinaryToNumber(String numberInput)
{
int remainder;
if (binarynumber <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
return 0;
}
}
}
As mentioned in my comments, your updated code contains two errors
while (i < input.length()); is an infinite loop, because it has no body. Therefore i cannot be increased and will stay lower than input.length().
inputString = inputKeyboard.next(); request another input after the first one and the first input will be ignored.
This is a fixed and commented version of your updated code:
public class Question1 {
public static void main(String[] args) {
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
//boolean BinaryNumber = false; // not needed anymore
//String inputString = ""; // not needed too
while (!checkInputCorrect(inputUser)) { // there is no reason for using a boolean var here .. directly use the returned value of this method
System.out.println("You have given me an invalid input. Please enter a binary number: "); // changed this message a little bit
inputUser = inputKeyboard.nextLine(); // re-use the "old" variable inputUser here
}
int finalNumber = binaryToNumber(inputUser);
System.out.println("Congratulations, your decimal number is " + finalNumber + ".");
}
public static boolean checkInputCorrect(String input) { // method names should start with a lower case letter
for (int i = 0; i < input.length(); i++) {
//while (i < input.length()); // this loop is deadly. Please think about why
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
//i++; // what is the purpose of this? The "for" loop will increment "i" for you
}
return true;
}
public static int binaryToNumber(String numberInput) { //method name ... lower case letter ;)
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}

binary to decimal program isn't giving correct answer java

So i have to write a program for homework where it takes a binary number and prints out its the decimal form. I've tried and and i just can't really get it. Like im printing out what it's doing every time in the loop and it looks like im getting the wrong value when i multiply the inputed data by the 2^i. If someone could help, that would be amazing
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
int value = 0;
int square_value = 0;
for (int i = 0; i < binary_number.length(); i++) {
char binary_place_holder = binary_number.charAt(i);
square_value = (int) Math.pow(2, i);
if (binary_place_holder == '1') {
value = (square_value*binary_place_holder+value);
}
System.out.println(binary_place_holder+ " " + square_value + " " + value);
}
System.out.print(binary_number + " == " + value);
}
}
The way you determine the exponent is wrong: The exponent is not i.
You need to realize that you are looking at the string from left to right side so from the highest bit.
This means the first character's exponent is 2^string_length-1.
Second character's exponent is 2^string_length-2 and so on.
Therefore as the index i becomes larger, i.e. as we are scanning the input left to right, the exponent value becomes smaller.
So the exponent is:
int exponent = binary_number.length() - 1 - i;
Note: You can of course do things in reverse and start from the end of the input string and determine the exponent that way, I just wanted to do less changes to your code.
Also, you should add a check to make sure the input is a valid binary number. You can write your own function to do it but a simpler solution is to use regex matching:
binary_number.matches("[01]+")
This will return true if the string binary_number contains only '0' and '1' characters, and false otherwise.
Applying all these changes to your code:
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner userinput = new Scanner(System.in);
System.out.println("Enter a binary number (only 1's or 0's): ");
String binary_number = userinput.next();
if(!binary_number.matches("[01]+")) {
System.err.println("\nPlease enter a valid binary number");
} else {
int value = 0;
for (int i = 0; i < binary_number.length(); i++) {
if (binary_number.charAt(i) == '1') {
int exponent = binary_number.length() - 1 - i;
value += (int) Math.pow(2, exponent);
}
}
System.out.print(binary_number + " == " + value);
}
}
This might be considered cheating but you could go all like
System.out.println(Integer.parseInt(binary_number, 2));

Binary to decimal conversion

I am a novice programmer trying to write a program that converts an entered Binary number into a decimal number. As far as I can tell, the math and code are right, and no compilation errors are returned, however the number that is output is NOT the correct decimal number. My code is as follows:
String num;
double result = 0;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number or enter 'quit' to quit: ");
num = in.nextLine();
int l = num.length();
if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
for (int i = 0; i < l; i++)
{
result = result + (num.charAt(i) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
} while (!num.equals("quit"));
if (num.equals("quit")){
System.out.println("You chose to exit the program.");
return;
}
Any Help you could give would be much appreciated. I tried making my question as clear as possible but if you have any questions I will try to answer the best I can. I have not been doing this long. All I need is for someone to look it over and hopefully find the error I made somewhere, thanks.
Change
result = result + (num.charAt(i) * Math.pow(2, (l - i)));
to
result = result + ((num.charAt(i) - '0') * Math.pow(2, i));
or more compactly,
result += (num.charAt(i) - '0') * Math.pow(2, i);
Remember that the character '0' is not the same thing as the number 0 (same for '1' and 1); num.charAt(i) returns the character not the integer.
int a = '0';
int b = 0;
System.out.println(Math.pow(2, a));
System.out.println(Math.pow(2, b));
Output:
2.81474976710656E14
1.0
Big difference isn't there?
The function String.charAt(); does not return the number 0 or 1 which you can multiply with the bit but the character "id". You need to convert the String / char to a number.
String num;
double result = 0;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number or enter 'quit' to quit: ");
num = in.nextLine();
int l = num.length();
if (num.indexOf("0")==-1 || num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
for (int i = 0; i < l; i++)
{
result = result + (Integer.parseInt(num.substring(i,i+1)) * Math.pow(2, (l - i)));
}
System.out.println("The resulting decimal number is: " +result);
} while (!num.equals("quit"));
if (num.equals("quit")){
System.out.println("You chose to exit the program.");
return;
}
By the way: Why is a string that does not contain either a 0 or a 1 not a binary numer? Think of 1111 for example. I think you should better check for "neither 0 nor 1"
if (num.indexOf("0")==-1 && num.indexOf("1")==-1 ){
System.out.println("You did not enter a binary number.");
}
Note that num.charAt(i) gives the ASCII code for the character at position i. This is not the value you want. You need to convert each character digit to an int before you do any math with the value.
Integer.parseInt(string, base) parse string into an integer using "base" radix, if it cannot be converted, it raises an exception.
import java.util.Scanner;
public class Convertion {
public static void main(String[] args) {
String num;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a binary number");
num = in.nextLine();
try{
//this does the conversion
System.out.println(Integer.parseInt(num, 2));
} catch (NumberFormatException e){
System.out.println("Number entered is not binary");
}
}
}

Categories

Resources