Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class BinToHex {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String binInput = scanner.nextLine();
- switch (binInput.length() % 4) {
- case 0: break;
- case 1: binInput = "000" + binInput; break;
- case 2: binInput = "00" + binInput; break;
- case 3: binInput = "0" + binInput; break;
- }
- StringBuilder hexOut = new StringBuilder();
- for (int i = 0; i < binInput.length(); i+=4) {
- StringBuilder tempBuild = new StringBuilder();
- tempBuild = tempBuild.append(binInput.charAt(i));
- tempBuild = tempBuild.append(binInput.charAt(i+1));
- tempBuild = tempBuild.append(binInput.charAt(i+2));
- tempBuild = tempBuild.append(binInput.charAt(i+3));
- switch (tempBuild.toString()) {
- case "0000": hexOut.append("0"); break;
- case "0001": hexOut.append("1"); break;
- case "0010": hexOut.append("2"); break;
- case "0011": hexOut.append("3"); break;
- case "0100": hexOut.append("4"); break;
- case "0101": hexOut.append("5"); break;
- case "0110": hexOut.append("6"); break;
- case "0111": hexOut.append("7"); break;
- case "1000": hexOut.append("8"); break;
- case "1001": hexOut.append("9");; break;
- case "1010": hexOut.append("A"); break;
- case "1011": hexOut.append("B"); break;
- case "1100": hexOut.append("C"); break;
- case "1101": hexOut.append("D"); break;
- case "1110": hexOut.append("E"); break;
- case "1111": hexOut.append("F"); break;
- }
- }
- System.out.println(hexOut);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement