Created
April 1, 2019 12:55
-
-
Save landjd19/1483938ea7e26889eceeaa411f85cccc to your computer and use it in GitHub Desktop.
Binary Convert
This file contains 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
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