Advertisement
dimipan80

Decimal to Binary Number

Aug 8th, 2014
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. /* Using loops write a program that converts an integer number to its binary representation.
  2.  * The input is entered as long. The output should be a variable of type string. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class _14_DecimalToBinaryNumber {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scanner = new Scanner(System.in);
  11.         System.out.print("Enter a Integer number: ");
  12.         long decNum = scanner.nextLong();
  13.         scanner.close();
  14.  
  15.         // Short variant:
  16.         // String binaryNum = Long.toBinaryString(decNum);
  17.  
  18.         String binaryNum = convertDecimalNumberToBinaryString(decNum);
  19.  
  20.         System.out.println("That Decimal number in Binary system is: " + binaryNum);
  21.     }
  22.  
  23.     private static String convertDecimalNumberToBinaryString(long number) {
  24.         // TODO Auto-generated method stub
  25.         String result = "";
  26.         do {
  27.             if ((number & 1) == 0) {
  28.                 result = "0" + result;
  29.             } else {
  30.                 result = "1" + result;
  31.             }
  32.  
  33.             number >>>= 1;
  34.         } while (number > 0);
  35.  
  36.         return result;
  37.     }
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement