Skip to content

Instantly share code, notes, and snippets.

@landjd19
Created April 1, 2019 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save landjd19/1483938ea7e26889eceeaa411f85cccc to your computer and use it in GitHub Desktop.
Save landjd19/1483938ea7e26889eceeaa411f85cccc to your computer and use it in GitHub Desktop.
Binary Convert
import java.util.*;
public class BinaryConvert
{
Scanner sc = new Scanner(System.in);
public BinaryConvert(){
System.out.println("Press 1 to convert decimal to binary, press 2 to do the opposite.");
int which = sc.nextInt();
if(which == 1){
System.out.println("Please input your decimal number: ");
int dec = sc.nextInt();
ArrayList<Integer> newNum = new ArrayList<Integer>();
while(dec >= 1){
if(dec % 2 == 0){
newNum.add(0);
}else{
newNum.add(1);
}
dec /= 2;
}
System.out.println("Number in binary: " + newNum);
}else if(which == 2){
System.out.println("Please input your binary number: ");
int bin = sc.nextInt();
int place = 1;
int newNum = 0;
while(bin >= 1){
if(bin % 10 == 1){
newNum += place;
}
place *= 2;
bin /= 10;
}
System.out.println("Number in decimal: " + newNum);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment