Jump to content

decimal to binary number

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
11 replies to this topic

#1
AstralX

AstralX

    Newbie

  • Members
  • Pip
  • 7 posts
Ok. this is my first tutorial so i hope that you will understand.
How this programme works:
  • Input - decimal number
  • output - binary number

So here is code:

import java.util.*;


public class number

{

	public static void main (String [] args)

	{

		Scanner input = new Scanner (System.in);

		System.out.println ("Input decimal number");

		int decimal = input.nextInt ();

		input.close ();

		

		int base = 2;

		int result = 0;

		int multiplier = 1;

		

		while (decimal>0)

		{

			int residue = decimal%base;

			decimal = decimal/base;

			result = result +residue*multiplier;

			multiplier = multiplier * 10;

		}

		System.out.println ("binary....."+result);

	}

}


When i try it it was working although there can be some mistake so try it.

#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
Input decimal number
1000000
binary.....1253788736


Nope, doesn't work.

#3
curse

curse

    Newbie

  • Members
  • PipPip
  • 22 posts
Just whipped this up in a few minutes. It seems to work, although it could probably be re-factored.

EDIT: Re-factored a bit.
public int BinaryToDecimal(int bin)
{
    /* Base cases */
    if (bin == 0) return 0;
    if (bin == 1) return 1;
		
    /* Store the binary number as a String. */
    String number = Integer.toString(bin);

    /* Most- and least-significant digits */
    int MSD = (int)(java.lang.Math.pow(2, number.length()-1));
    int LSDs = Integer.parseInt(number.substring(1));
	
    /* Recursion */
    return MSD + BinaryToDecimal(LSDs);
}

Unit tests:
0 to decimal is: 0
1 to decimal is: 1
1111 to decimal is: 15
1000000 to decimal is: 64
11110000 to decimal is: 240


I realize that this method is not the most efficient method, however I think it's a good demonstration of how and when recursion can be used. ^^

@OP:
  • You should unit-test your program before saying that it works. Trying 1 or 2 similar cases is not enough. You need to try to BREAK your code.
  • Never put computations in the main() method... That completely contradicts the reason Java exists.

Edited by curse, 04 March 2010 - 04:15 PM.


#4
unscripted_1

unscripted_1

    Newbie

  • Members
  • PipPip
  • 12 posts
I tried to do this exact same thing a few nights ago! I'm a bit older, & pretty useless at even pretty simple math problems sometimes, so I ran into a problem...

Here's my question: how big should an array be to store a decimal number as binary? I kept thinking it's 2n or something, but nahhh obviously not.
Here's the method I came up with to solve the problem (the array would have to be printed backwards to get the right answer, i realize that much):

 
public void convert(int number) {

   int[] binaryArray = new int[?WHAT_SIZE?];
   int i = 0;

   while (number > 0) {
      
      binaryArray[i] = number % 2;
      number = number / 2;
      i++;

   } 
}

Edited by unscripted_1, 21 April 2010 - 09:25 PM.
duhhhh


#5
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
That's just awful, why would you want to store the binary string in an int array? Much better way would be to use a String.

Every integer is 4 bytes long, your binary digit could take take 4 times less space and be stored in a byte.
Ideally, it would only need a bit to store one binary digit, but processors don't manipulate single bits, and this would require additional operations to display.


there's already a method for that, no need to figure that out yourself:

Integer.toString(decimal, 2);
or

Integer.toBinaryString(decimal);

Edited by Sinipull, 22 April 2010 - 05:55 AM.


#6
curse

curse

    Newbie

  • Members
  • PipPip
  • 22 posts

unscripted_1 said:

I tried to do this exact same thing a few nights ago! I'm a bit older, & pretty useless at even pretty simple math problems sometimes, so I ran into a problem...

Here's my question: how big should an array be to store a decimal number as binary? I kept thinking it's 2n or something, but nahhh obviously not.
Here's the method I came up with to solve the problem (the array would have to be printed backwards to get the right answer, i realize that much):

 
public void convert(int number) {

   int[] binaryArray = new int[?WHAT_SIZE?];
   int i = 0;

   while (number > 0) {
      
      binaryArray[i] = number % 2;
      number = number / 2;
      i++;

   } 
}

Just look up some basic binary conversion algorithm... Understand how to get to and from binary on paper, then write out the logic.

#7
unscripted_1

unscripted_1

    Newbie

  • Members
  • PipPip
  • 12 posts
yea I came to that conclusion myself while I was thinking about it at work tonight. Sigh, but of course there's already a function that returns your int as a binary String. Everything's already been written by someone at some time :)

#8
curse

curse

    Newbie

  • Members
  • PipPip
  • 22 posts

unscripted_1 said:

yea I came to that conclusion myself while I was thinking about it at work tonight. Sigh, but of course there's already a function that returns your int as a binary String. Everything's already been written by someone at some time :)

Of course. However, one of my software engineering professors really liked to give us assignments where we would code stuff that was pretty commonplace in the programming world. It was good practice to become familiar with the language and how things actually work.

Besides, if you ever work professionally with code, 90-95% of all your project's code is probably copy-pasted from somewhere else. Like the code for a TCP connection... No one really bothers to memorize it, they just pull it up and copy it over.

#9
unscripted_1

unscripted_1

    Newbie

  • Members
  • PipPip
  • 12 posts
My professor was the same, he liked us to write our own versions of already existing methods & functions, as it's awesome practice.
re: Storing a binary number as an int array... I know it's pretty ghastly at first sight. I was writing a wierd little program late at night when I came up with it. The idea behind it is 'what if you want to actually do something different with the binary? Rather than just print it?'. It seemed easier to me to work with it as an array for some reason...

#10
curse

curse

    Newbie

  • Members
  • PipPip
  • 22 posts

unscripted_1 said:

My professor was the same, he liked us to write our own versions of already existing methods & functions, as it's awesome practice.
re: Storing a binary number as an int array... I know it's pretty ghastly at first sight. I was writing a wierd little program late at night when I came up with it. The idea behind it is 'what if you want to actually do something different with the binary? Rather than just print it?'. It seemed easier to me to work with it as an array for some reason...

It might be easier for you to work with arrays but it's rather costly in terms of resources. If you know the proper method calls for the String class, it's just as easy to do the same thing with a String.

#11
unscripted_1

unscripted_1

    Newbie

  • Members
  • PipPip
  • 12 posts
thanks for all the advice curse, don't stop posting :D :D

#12
GMVResources

GMVResources

    Learning Programmer

  • Members
  • PipPipPip
  • 72 posts
It really matters with the person curse.