Skip to content

Instantly share code, notes, and snippets.

@iamgauravbisht
Created December 29, 2023 12:41
Show Gist options
  • Save iamgauravbisht/a6fdbfcf85aaacc8f3e88bdba04c2543 to your computer and use it in GitHub Desktop.
Save iamgauravbisht/a6fdbfcf85aaacc8f3e88bdba04c2543 to your computer and use it in GitHub Desktop.
converter for decimal to binary and binary to decimal
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