Created
December 29, 2023 12:41
-
-
Save iamgauravbisht/a6fdbfcf85aaacc8f3e88bdba04c2543 to your computer and use it in GitHub Desktop.
converter for decimal to binary and binary to decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Bitwise; | |
import java.util.Scanner; | |
class Converter{ | |
public String toBinary(int n) { | |
String result = ""; | |
while(n != 0){ | |
int lastbit = n & 1; | |
result = lastbit + result; | |
n = n >> 1; | |
} | |
return result; | |
} | |
public int toDecimal(int n){ | |
int result=0; | |
int index=0; | |
while( n != 0 ){ | |
int lastdigit = n % 10; | |
if(lastdigit==1){ | |
result += (int) Math.pow(2,index); | |
} | |
n = n / 10; | |
index++; | |
} | |
return result; | |
} | |
} | |
public class DecimalToBinary { | |
public static void main(String[] args) { | |
Scanner s=new Scanner(System.in); | |
Converter i =new Converter(); | |
System.out.print("Enter a decimal number : "); | |
int decimal = s.nextInt(); | |
String B = i.toBinary(decimal); | |
System.out.println("Binary : " + B ); | |
System.out.print("Enter a binary number : "); | |
int binary = s.nextInt(); | |
int D= i.toDecimal(binary); | |
System.out.println("Decimal : " + D); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment