Java Binary to Decimal Format/ How to assign a proper input? - java

I'm writing a java program to convert binary numbers into decimal numbers, I've managed to get my program to work in that regard.
My question is how do I make it so the user has to enter a binary number or else an error will pop up and the question will end?
Also, How do I repeat my statement so the user can calculate multiple binary number conversions?
If you give an answer could you explain how each step works and show how the code should looks?
My current program is this:
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
int binarynum =input.nextInt();
int binary=binarynum;
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
System.out.println("Binary = "+binarynum+" Decimal = "+decimal); ;
}

This version keeps on asking the user to give a binary value.
If it's not binary, an exception will be thrown.
Finally, to stop the process, you just have to enter END as input.
public static void main(String[] args) {
while (true) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary number (END to exit): ");
try {
String inputValue = input.next();
if (inputValue.equals("END")) {
break;
}
if (!inputValue.matches("[01]+")) {
throw new Exception("Invalid binary input");
}
int binarynum = Integer.valueOf(inputValue);
int decimal = getDecimalValue(binarynum);
System.out.println("Binary = " + binarynum + " Decimal = " + decimal);
System.out.println();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
public static int getDecimalValue(int binary) {
int decimal = 0;
int power = 0;
while (true) {
if (binary == 0) {
break;
} else {
int temp = binary % 10;
decimal += temp * Math.pow(2, power);
binary = binary / 10;
power++;
}
}
return decimal;
}

You can use Scanner.hasNextInt(int radix) and Scanner.nextInt(int radix) with a radix of 2. Of course nextInt(2) would do all your work, so:
System.out.println("Enter a binary number:");
while (!input.hasNextInt(2)) {
System.out.println("Only 0 and 1 allowed. Enter a binary number:");
input.nextLine(); // Skip the input line.
}
int binarynum = input.nextInt(); // input.nextInt(2) would give the result.
Scanner has for its next...() methods corresponding test methods hasNext...().

Related

How can I test if a string contains 0 or 1, then convert it from binary to decimal?

I have to create a conversion method that analyzes if the characters in a string are 1 and/or 0, then include that character in a conversion from binary to decimal. Then I have to use a try-catch block to prompt the user for a binary number, and convert the number within the try-catch block and print the converted number to the console. Right now, I can't seem to get the code to return the converted decimal, or the BinaryFormatException.
This is what I have so far:
import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String binaryString;
int decimalNumber = 0;
try {
System.out.print("Please enter the binary number to convert: ");
binaryString = input.nextLine();
convertBinary(String.valueOf(decimalNumber));
System.out.println("Your number converted to decimal is " + binaryString + ".");
} catch (BinaryFormatException e) {
System.out.println(e.getMessage());
}
}
static int convertBinary(String binaryString) throws BinaryFormatException {
int decimalNumber = 0;
int n = 0;
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString.matches("[01]+")) {
throw new BinaryFormatException("Improper formatting for character: " + i + ".");
}
else {
int temp = i%10;
decimalNumber += temp*Math.pow(2, i);
i = i/10;
i++;
}
}
}
}
you missed return statement...
i suggest you use a ide, not a notepad
static int convertBinary(String binaryString) throws BinaryFormatException {
int decimalNumber = 0;
int n = 0;
for (int i = 0; i < binaryString.length(); i++) {
if (binaryString.matches("[01]+")) {
throw new BinaryFormatException("Improper formatting for character: " + i + ".");
}
else {
int temp = i%10;
decimalNumber += temp*Math.pow(2, i);
i = i/10;
i++;
}
}
**return decimalNumber;**
}
1.Your "convertBinary" method has no return value, you need to return an Integer.
2."BinaryFormatException" is a custom Exeption, you need to make a class for it like this:
private static class BinaryFormatException extends Exception {
public BinaryFormatException(String err){
super(err);
}
}
3.You can use the parseInt method of Ineger to convert to decimal, since it supports numeral systems as second parameter e.g.:
int i=Integer.parseInt("11", 2);
Why don't you use standard lib from Java.
Also be careful about the length of the binaryString. If too long, then it cannot be parsed to int and you might need to use long.
String binaryString = "111001111111111";
if (binaryString.length() >= 31) {
// don't forget to check the string length
//
// throw some error, or use long instead of integer
}
try {
int value = Integer.parseInt(binaryString, /* radix */ 2);
System.out.println(value); // 29695
} catch (NumberFormatException ex) {
// binaryString contains something that is not 1 or 0
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
try
{
System.out.println("Enter binary:");
String stringOfBinary = scanner.nextLine().trim();
int decimalNumber = convertToDecimal(stringOfBinary);
System.out.println("Your number converted to decimal is " + decimalNumber + ".");
}
catch (NumberFormatException bfe)
{
System.out.println(bfe);
}
}
static int convertToDecimal(String binary) throws NumberFormatException
{
if (!binary.matches("^[0-1]*$"))
throw new NumberFormatException("Improper formatting for input string: "+binary);
return Integer.valueOf(binary, 2);
}
Make sure you replace NumberFormatException with your exception.

Array not Recognized

My program is to enter 10 numbers and add them together then display the result. Then I am to divide the smaller number by the larger number and display the result. Users cannot enter characters or zero.
I am new and have been working on this for DAYS. I do not see my mistake.
Now my problem is the Variable i isn't being recognized.
I introduced an Exception (try..catch) and it wouldn't read. I tried moving things all over (I'm new, I'm guessing and seeing what does what..) I did something wrong and probably something stupidly small. I need some help and fresh eyes.
I also need to end the program when the user enters 9999. Any idea where that would go? 'Cause I'm about to break out into tears.
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
System.out.print("Please Enter Ten Numbers:");
System.out.println();
try{
for (int i = 1; i < digit.length; i++)
System.out.print("Numbers " + i + ": ");
digit[i] = (double)in.nextInt(); //Array Not recognized here
sum += (int)digit[i];//Or recognized here
// Input the data into array from the user.
if(digit[i]==0.0)//None of these are recognized either, what did I do?
{
System.out.println("You can't enter zero. Try again");
--i; //nope
in.nextLine();//dispose of wrong number
}
}catch (NumberFormatException e){
System.out.println("You Can Only Enter Numbers!");
--i; //nope, not recognizing here either
in.nextLine();//dispose of wrong input
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
//These are all good and recognized. No problem with the division part
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
}
You for loop doesn't have braces around it. Only the first line below it is part of the loop.
You need braces around the contents of your for loop.
I have tried to modified the attached code snippet. Hope this might help you.
package com.so.general;
import java.util.Scanner;
public class AddNumbers
{
private static final int SIZE_OF_ARRAY = 10;
public static void main(String[] args)
{
int counter = 0;
double sumOfTenDigits = 0.0;
double[] digit = new double[SIZE_OF_ARRAY];
int listOfElements = digit.length;
System.out.print("Please Enter Ten Numbers:"+"\n");
Scanner readInputFromUser = new Scanner(System.in);
try
{
for (counter=0; counter<listOfElements; counter++)
{
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
if(digit[counter] == 0.0)
{
System.out.println("Zero is not allowed. Please try again.");
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
}
sumOfTenDigits += digit[counter];
}
}
catch(NumberFormatException numberFormatExcep)
{
System.err.println(" You have entered other than numbers. Only numbers are allowed. Terminating the program.");
numberFormatExcep.printStackTrace();
System.exit(0);
}
System.out.println("Addition is: "+ sumOfTenDigits);
System.out.println("Would you like to divide the values? Press Y to continue, any other character to terminate the program.");
Scanner continueWithDivide = new Scanner(System.in);
String userInput = continueWithDivide.nextLine();
closeScanner(readInputFromUser);
closeScanner(continueWithDivide);
if(readInputFromUser != null)
{
readInputFromUser.close();
}
// Always use static string literals on the left hand side.
// This prevents Null pointer exception.
if("Y".equalsIgnoreCase(userInput))
{
double[] divisionResult = new double[listOfElements/2];
for(int i=0; i<listOfElements; i+=2)
{
double result = digit[i];
if (result > digit[i+1])
{
result = result/digit[i+1];
}
else
{
result = digit[i+1]/result;
}
divisionResult[i/2] = result;
System.out.println(result);
}
}
else
{
System.out.println("You have entered "+userInput+". Terminating the program.");
System.exit(0);
}
}
/**
* Closed the scanner
* #param scanner
*/
public static void closeScanner(Scanner scanner)
{
if(scanner != null)
{ try
{
scanner.close();
}
catch(IllegalStateException illegatStateExcep)
{
System.err.println("Scanner is already closed.");
illegatStateExcep.printStackTrace();
}
}
}
Please note the below points:
Always use proper indentation.
Always match { }
Even if your if or for is having only one statement, use { }.
For example:
for (int counter=1; i<digit.length; i++)
{
System.out.print("Numbers " + i + ": ");
}
Above three points will save a lot of your time if some thing goes wrong in your program.
Use proper name for the variables and method.
Always close the IO resources after the use.
For example:
if(scanner != null)
{
scanner.close();
}

Convert binary to decimal with an array

Im trying to make a binary string into a decimal. It will terminate if -1 is entered. I am stuck with using an array. It was suggested to use: public static int binaryToDecimal (String binaryString) . But Im not sure how to do that. This is what I have:
import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (inString != "-1") {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = 0, decimal = 0; i < binaryLength; i++) {
decimal = decimal * 2 + (inString[i] - 0);
System.out.print(decimal);
}
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
It says there is a compilation problem with the array. Thank you!
inString is a String, not an array. So, you can't use inString[i]. To get the character at a given position in the string, use inString.charAt(i), which returns a char.
Then, you'll also have to convert that char into an int.
You can do this with Character.getNumericValue(char).
So in summary, instead of
inString[i]
you need to use
Character.getNumericValue(inString.charAt(i))
Try this one:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
//Character.getNumericValue(inString.charAt(i))
while (inString != "-1") {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = 0, decimal = 0; i < binaryLength; i++)
{
decimal = decimal * 2 + (Character.getNumericValue(inString.charAt(i)) - 0);
System.out.print(decimal);
}
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
}
As suggested, you have to use Character.getNumericValue
You can simplify the code by using Integer.parseInt():
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
String inString;
while (true) {
System.out.println("Enter a binary number: ");
inString = input.nextLine();
if (inString.equals("-1"))
break;
System.out.println(Integer.parseInt(inString, 2));
}
System.out.println("All set !");
}
You had few logical and few syntax errors.
This is working code :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inString;
int decimal;
System.out.println("Enter a binary number: ");
inString = input.nextLine();
while (!"-1".equals(inString)) {
int i;
int binaryLength;
binaryLength = inString.length();
for (i = binaryLength-1, decimal = 0; i >= 0; i--) {
if (inString.charAt(i) == '1') {
decimal += Math.pow(2, binaryLength-i-1);
}
}
System.out.println(decimal);
System.out.println("Enter a binary number: ");
inString = input.nextLine();
}
System.out.println("All set !");
}
Note that comparing String cannot be done with ==, you have to use equals or compareTo methods.
byte[] binary = {1,1,0,1};
int decimal = 0;
for(int i=binary.length-1, j=0; i>=0; i--, j++){
decimal += binary[i]*Math.pow(2, j);
}

Converting Decimal to Binary Java

I am trying to convert decimal to binary numbers from the user's input using Java.
I'm getting errors.
package reversedBinary;
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(number));
}
}
private static Object binaryform(int number) {
int remainder;
if (number <=1) {
System.out.print(number);
}
remainder= number %2;
binaryform(number >>1);
System.out.print(remainder);
{
return null;
} } }
How do I convert Decimal to Binary in Java?
Integer.toBinaryString() is an in-built method and will do quite well.
Integer.toString(n,8) // decimal to octal
Integer.toString(n,2) // decimal to binary
Integer.toString(n,16) //decimal to Hex
where n = decimal number.
Your binaryForm method is getting caught in an infinite recursion, you need to return if number <= 1:
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number = in.nextInt();
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
System.out.print("Convert to binary is:");
//System.out.print(binaryform(number));
printBinaryform(number);
}
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number % 2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
I just want to add, for anyone who uses:
String x=Integer.toBinaryString()
to get a String of Binary numbers and wants to convert that string into an int. If you use
int y=Integer.parseInt(x)
you will get a NumberFormatException error.
What I did to convert String x to Integers, was first converted each individual Char in the String x to a single Char in a for loop.
char t = (x.charAt(z));
I then converted each Char back into an individual String,
String u=String.valueOf(t);
then Parsed each String into an Integer.
Id figure Id post this, because I took me a while to figure out how to get a binary such as 01010101 into Integer form.
/**
* #param no
* : Decimal no
* #return binary as integer array
*/
public int[] convertBinary(int no) {
int i = 0, temp[] = new int[7];
int binary[];
while (no > 0) {
temp[i++] = no % 2;
no /= 2;
}
binary = new int[i];
int k = 0;
for (int j = i - 1; j >= 0; j--) {
binary[k++] = temp[j];
}
return binary;
}
public static void main(String h[])
{
Scanner sc=new Scanner(System.in);
int decimal=sc.nextInt();
String binary="";
if(decimal<=0)
{
System.out.println("Please Enter greater than 0");
}
else
{
while(decimal>0)
{
binary=(decimal%2)+binary;
decimal=decimal/2;
}
System.out.println("binary is:"+binary);
}
}
The following converts decimal to Binary with Time Complexity : O(n) Linear Time and with out any java inbuilt function
private static int decimalToBinary(int N) {
StringBuilder builder = new StringBuilder();
int base = 2;
while (N != 0) {
int reminder = N % base;
builder.append(reminder);
N = N / base;
}
return Integer.parseInt(builder.reverse().toString());
}
In C# , but it's just the same as in Java :
public static void findOnes2(int num)
{
int count = 0; // count 1's
String snum = ""; // final binary representation
int rem = 0; // remainder
while (num != 0)
{
rem = num % 2; // grab remainder
snum += rem.ToString(); // build the binary rep
num = num / 2;
if (rem == 1) // check if we have a 1
count++; // if so add 1 to the count
}
char[] arr = snum.ToCharArray();
Array.Reverse(arr);
String snum2 = new string(arr);
Console.WriteLine("Reporting ...");
Console.WriteLine("The binary representation :" + snum2);
Console.WriteLine("The number of 1's is :" + count);
}
public static void Main()
{
findOnes2(10);
}
It might seem silly , but if u wanna try utility function
System.out.println(Integer.parseInt((Integer.toString(i,2))));
there must be some utility method to do it directly, I cant remember.
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
System.out.print("Put a number : ");
int a=in.nextInt();
StringBuffer b=new StringBuffer();
while(a>=1)
{
if(a%2!=0)
{
b.append(1);
}
else if(a%2==0)
{
b.append(0);
}
a /=2;
}
System.out.println(b.reverse());
}
Binary to Decimal without using Integer.ParseInt():
import java.util.Scanner;
//convert binary to decimal number in java without using Integer.parseInt() method.
public class BinaryToDecimalWithOutParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
int binarynum =input.nextInt();
int binary=binarynum;
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
System.out.println("Binary="+binarynum+" Decimal="+decimal); ;
}
}
Output:
Enter a binary number:
1010
Binary=1010 Decimal=10
Binary to Decimal using Integer.parseInt():
import java.util.Scanner;
//convert binary to decimal number in java using Integer.parseInt() method.
public class BinaryToDecimalWithParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
String binaryString =input.nextLine();
System.out.println("Result: "+Integer.parseInt(binaryString,2));
}
}
Output:
Enter a binary number:
1010
Result: 10
A rather simple than efficient program, yet it does the job.
Scanner sc = new Scanner(System.in);
System.out.println("Give me my binaries");
int str = sc.nextInt(2);
System.out.println(str);
All your problems can be solved with a one-liner!
To incorporate my solution into your project, simply remove your binaryform(int number) method, and replace System.out.print(binaryform(number)); with System.out.println(Integer.toBinaryString(number));.
/**
* converting decimal to binary
*
* #param n the number
*/
private static void toBinary(int n) {
if (n == 0) {
return; //end of recursion
} else {
toBinary(n / 2);
System.out.print(n % 2);
}
}
/**
* converting decimal to binary string
*
* #param n the number
* #return the binary string of n
*/
private static String toBinaryString(int n) {
Stack<Integer> bits = new Stack<>();
do {
bits.push(n % 2);
n /= 2;
} while (n != 0);
StringBuilder builder = new StringBuilder();
while (!bits.isEmpty()) {
builder.append(bits.pop());
}
return builder.toString();
}
Or you can use Integer.toString(int i, int radix)
e.g:(Convert 12 to binary)
Integer.toString(12, 2)
public static String convertToBinary(int dec)
{
String str = "";
while(dec!=0)
{
str += Integer.toString(dec%2);
dec /= 2;
}
return new StringBuffer(str).reverse().toString();
}
Practically you can write it as a recursive function. Each function call returns their results and add to the tail of the previous result. It is possible to write this method by using java as simple as you can find below:
public class Solution {
private static String convertDecimalToBinary(int n) {
String output = "";
if (n >= 1) {
output = convertDecimalToBinary(n >> 1) + (n % 2);
}
return output;
}
public static void main(String[] args) {
int num = 125;
String binaryStr = convertDecimalToBinary(num);
System.out.println(binaryStr);
}
}
Let us take a look how is the above recursion working:
After calling convertDecimalToBinary method once, it calls itself till the value of the number will be lesser than 1 and return all of the concatenated results to the place where it called first.
References:
Java - Bitwise and Bit Shift Operators https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
If you want to reverse the calculated binary form , you can use the StringBuffer class and simply use the reverse() method . Here is a sample program that will explain its use and calculate the binary
public class Binary {
public StringBuffer calculateBinary(int number) {
StringBuffer sBuf = new StringBuffer();
int temp = 0;
while (number > 0) {
temp = number % 2;
sBuf.append(temp);
number = number / 2;
}
return sBuf.reverse();
}
}
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("enter the number you want to convert");
BufferedReader bReader = new BufferedReader(newInputStreamReader(System.in));
int number = Integer.parseInt(bReader.readLine());
Binary binaryObject = new Binary();
StringBuffer result = binaryObject.calculateBinary(number);
System.out.println(result);
}
}
The better way of doing it:
public static void main(String [] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine().trim());
double ans = 0;
int i=0;
while(t!=0){
int digit = t & 1;
ans = ans + (digit*Math.pow(10,i));
i++;
t =t>>1;
}
System.out.println((int)ans);
}
I just solved this myself, and I wanted to share my answer because it includes the binary reversal and then conversion to decimal. I'm not a very experienced coder but hopefully this will be helpful to someone else.
What I did was push the binary data onto a stack as I was converting it, and then popped it off to reverse it and convert it back to decimal.
import java.util.Scanner;
import java.util.Stack;
public class ReversedBinary
{
private Stack<Integer> st;
public ReversedBinary()
{
st = new Stack<>();
}
private int decimaltoBinary(int dec)
{
if(dec == 0 || dec == 1)
{
st.push(dec % 2);
return dec;
}
st.push(dec % 2);
dec = decimaltoBinary(dec / 2);
return dec;
}
private int reversedtoDecimal()
{
int revDec = st.pop();
int i = 1;
while(!st.isEmpty())
{
revDec += st.pop() * Math.pow(2, i++);
}
return revDec;
}
public static void main(String[] args)
{
ReversedBinary rev = new ReversedBinary();
System.out.println("Please enter a positive integer:");
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
{
int input = Integer.parseInt(sc.nextLine());
if(input < 1 || input > 1000000000)
{
System.out.println("Integer must be between 1 and 1000000000!");
}
else
{
rev.decimaltoBinary(input);
System.out.println("Binary to reversed, converted to decimal: " + rev.reversedtoDecimal());
}
}
}
}
import java.util.*;
public class BinaryNumber
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number");
int n = scan.nextInt();
int rem;
int num =n;
String str="";
while(num>0)
{
rem = num%2;
str = rem + str;
num=num/2;
}
System.out.println("the bunary number for "+n+" is : "+str);
}
}
This is a very basic procedure, I got this after putting a general procedure on paper.
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number:");
int number = input.nextInt();
while(number!=0)
{
if(number%2==0)
{
number/=2;
System.out.print(0);//Example: 10/2 = 5 -> 0
}
else if(number%2==1)
{
number/=2;
System.out.print(1);// 5/2 = 2 -> 1
}
else if(number==2)
{
number/=2;
System.out.print(01);// 2/2 = 0 -> 01 ->0101
}
}
}
}
//converts decimal to binary string
String convertToBinary(int decimalNumber){
String binary="";
while(decimalNumber>0){
int remainder=decimalNumber%2;
//line below ensures the remainders are reversed
binary=remainder+binary;
decimalNumber=decimalNumber/2;
}
return binary;
}
One of the fastest solutions:
public static long getBinary(int n)
{
long res=0;
int t=0;
while(n>1)
{
t= (int) (Math.log(n)/Math.log(2));
res = res+(long)(Math.pow(10, t));
n-=Math.pow(2, t);
}
return res;
}
Even better with StringBuilder using insert() in front of the decimal string under construction, without calling reverse(),
static String toBinary(int n) {
if (n == 0) {
return "0";
}
StringBuilder bldr = new StringBuilder();
while (n > 0) {
bldr = bldr.insert(0, n % 2);
n = n / 2;
}
return bldr.toString();
}
No need of any java in-built functions. Simple recursion will do.
public class DecimaltoBinaryTest {
public static void main(String[] args) {
DecimaltoBinary decimaltoBinary = new DecimaltoBinary();
System.out.println("hello " + decimaltoBinary.convertToBinary(1000,0));
}
}
class DecimaltoBinary {
public DecimaltoBinary() {
}
public int convertToBinary(int num,int binary) {
if (num == 0 || num == 1) {
return num;
}
binary = convertToBinary(num / 2, binary);
binary = binary * 10 + (num % 2);
return binary;
}
}
int n = 13;
String binary = "";
//decimal to binary
while (n > 0) {
int d = n & 1;
binary = d + binary;
n = n >> 1;
}
System.out.println(binary);
//binary to decimal
int power = 1;
n = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
n = n + Character.getNumericValue(binary.charAt(i)) * power;
power = power * 2;
}
System.out.println(n);

decimal to binary in java

I'm having trouble in getting the binary. I do not know what's wrong. The binary number always ends up in gibberish. Also some parts like the new int[31] thing was from HW but I can't get around to make print the actual binary.
public class DectoBinary {
public static void main(String[]args) {
Scanner CONSOLE = new Scanner(System.in);
System.out.print("Please enter a nonnegative integer: ");
int value = CONSOLE.nextInt();
while (value < 0) {
System.out.print("number outside range.");
System.out.print
("Please enter a nonnegative interger more than 0: ");
value = CONSOLE.nextInt();
}
int[] intArray = new int[31];
decimalToBinary(value, intArray);
System.out.println(value + "" + intArray);
}
public static int[] decimalToBinary(int value, int[]intArray) {
int i = 0;
while (value != 0) {
if (value % 2 == 1)
intArray[i] = 1;
else
intArray[i] = 0;
value /= 2;
i++;
}
return intArray;
}
}
I think the error is on this line:
System.out.println(value + "" + intArray);
You cannot print an array of integers like this: you should either convert it to string, or write a loop that prints the array digit by digit:
for (int i : inrArray) {
System.out.print(intArray[i]);
}
System.out.println();
You do not need to pass in the output array as well: you can create it inside the function.
public static int[] decimalToBinary(int value) {
int count = 1;
int tmp = value;
while (tmp != 0) {
tmp /= 2;
count++;
}
int[] intArray = new int[count];
// Do the conversion here...
return intArray;
}
You can simply use Integer.toBinaryString(int).
Actually the is a very simple way to get binary numbers in java using BigInteger
public String dectoBin(int num){
String s = ""+num;
BigInteger bi = new BigInteger(s);
String bin = bi.toString(2);
return bin
}
BigInteger.toString(2) returns the number stored on the numerical base specified inside the parenthesis. Is a very easy way to get arround this problems.
System.out.println(value + "" + intArray);
the 'intArray' is a arrays's address, so, if you want to get actual binary you can use Arrays.toString(intArray)
As dasblinkenlight you need to print the array item by item. If you want a nice alternative, you can use a recursive printing of value mod 2 (modulo 2 gives you 1 or 0)
/** print directly*/
public static void decimalToBinary(int value) {
if(value > 1){
System.out.print(decimalToBinary(value/2) + "" + (value%2));
/**recursion with implicit cast to string*/
} else {
System.out.print( (value==0)?"":"1");
}
}
It works with any Base
Well actually to print the array, because all the slots in the array are initialized at 0 you need to detect where the first one begins, so.
you need to replace
System.out.println(value + "" + intArray);
with something like this;
System.out.println(vale + " ");
boolean sw = false;
for(int i=0;i<intArray.length;i++){
if(!sw)
sw = (intArray[i]==1);//This will detect when the first 1 appears
if(sw)
System.out.println(intArray[1]); //This will print when the sw changes to true everything that comes after
}
Here is a program to convert Decimal nos. into Binary.
import java.util.Scanner;
public class decimalToBinary {
static int howManyTerms (int n) {
int term = 0;
while (n != 0) {
term ++;
n /= 2;
}
return term;
}
static String revArrayofBin2Str (int[] Array) {
String ret = "";
for (int i = Array.length-1; i >= 0; i--)
ret += Integer.toString(Array[i]);
return ret;
}
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
System.out.print ("Enter any no.: ");
int num = sc.nextInt();
int[] bin = new int[howManyTerms (num)];
int dup = num, el = -1;
while (dup != 0) {
int rem = dup % 2;
bin [++el] = rem;
dup /= 2;
}
String d2b = revArrayofBin2Str(bin);
System.out.println("Binary of " + num + " is: " + d2b);
}
}
This is simple java code for decimal to binary using only primitive type int, hopefully it should help beginners.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DtoB {
public static void main(String[] args) {
try { // for Exception handling of taking input from user.
System.out.println("Please enter a number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int x = Integer.parseInt(input);
int bin = 0;
int p = 1;
while (x > 0) {
int r = x % 2;
bin = (r * p) + bin;
x = x / 2;
p *= 10;
}
System.out.println("Binary of " + input + " is = " + bin);
} catch (Exception e) {
System.out.println("Please enter a valid decimal number.");
System.exit(1);
e.printStackTrace();
}
}
}

Categories