From 80aa51daa22e321833ea34ae6f6180917786e411 Mon Sep 17 00:00:00 2001 From: Peterson Daronch de Bem Date: Sun, 18 Feb 2018 21:56:49 -0300 Subject: [PATCH] Add a bitwise conversion for DecimalToBinary. --- Conversions/DecimalToBinary.java | 71 +++++++++++++++++++++----------- 1 file changed, 48 insertions(+), 23 deletions(-) diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java index 671cedf201d2..176d27e03fe4 100644 --- a/Conversions/DecimalToBinary.java +++ b/Conversions/DecimalToBinary.java @@ -6,27 +6,52 @@ * @author Unknown * */ -class DecimalToBinary -{ - /** - * Main Method - * - * @param args Command Line Arguments - */ - public static void main(String args[]) - { - Scanner sc=new Scanner(System.in); - int n,k,s=0,c=0,d; - System.out.print("Decimal number: "); - n=sc.nextInt(); - k=n; - while(k!=0) - { - d=k%2; - s=s+d*(int)Math.pow(10,c++); - k/=2; - }//converting decimal to binary - System.out.println("Binary equivalent:"+s); - sc.close(); - } +class DecimalToBinary { + + /** + * Main Method + * + * @param args Command Line Arguments + */ + public static void main(String args[]) { + conventionalConversion(); + bitwiseConversion(); + } + + /** + * This method converts a decimal number + * to a binary number using a conventional + * algorithm. + */ + public static void conventionalConversion() { + int n, b = 0, c = 0, d; + Scanner input = new Scanner(System.in); + System.out.printf("Conventional conversion.\n\tEnter the decimal number: "); + n = input.nextInt(); + while (n != 0) { + d = n % 2; + b = b + d * (int) Math.pow(10, c++); + n /= 2; + } //converting decimal to binary + System.out.println("\tBinary number: " + b); + } + + /** + * This method converts a decimal number + * to a binary number using a bitwise + * algorithm + */ + public static void bitwiseConversion() { + int n, b = 0, c = 0, d; + Scanner input = new Scanner(System.in); + System.out.printf("Bitwise conversion.\n\tEnter the decimal number: "); + n = input.nextInt(); + while (n != 0) { + d = (n & 1); + b += d * (int) Math.pow(10, c++); + n >>= 1; + } + System.out.println("\tBinary number: " + b); + } + } pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy