-1

What is the easiest way to do this in Javascript? Currently my code is a giant switch block, is there an easier way?

Current code:

function convertBintoHex(input){
    input = ""+input;
    while(input.length < 8){
        input = "0" + input;
    }

    input = [input.substring(0,4),input.substring(4,8)];
    var output = "";

    for(var i in input){
        switch(input[i]){
            case "0000":
                output += 0;
                break;
            case "0001":
                output += 1;
                break;
            case "0010":
                output += 2;
                break;
            case "0011":
                output += 3;
                break;
            case "0100":
                output += 4;
                break;
            case "0101":
                output += 5;
                break;
            case "0110":
                output += 6;
                break;
            case "0111":
                output += 7;
                break;
            case "1000":
                output += 8;
                break;
            case "1001":
                output += 9;
                break;
            case "1010":
                output += 'A';
                break;
            case "1011":
                output += 'B';
                break;
            case "1100":
                output += 'C';
                break;
            case '1101':
                output += 'D';
                break;
            case '1110':
                output += 'E';
                break;
            case '1111':
                output += 'F';
                break;
        }
    }

    while(output.charAt(0) == 0 && output.length > 1){
        output = output.substring(1);
    }

    return "0x" + output;
}
2
  • 1
    Does this or this help? This is my personal favourite! Commented Feb 17, 2014 at 7:09
  • I searched for this 20 times using a bunch of different searches, couldn't find anything like that. OMG. Commented Feb 17, 2014 at 18:35

1 Answer 1

2

Using built-in functions:

parseInt('1010101010', 2).toString(16)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.