-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;
}
PitaJ
  • 12,969
  • 6
  • 36
  • 55
  • 1
    Does [*this*](http://stackoverflow.com/questions/17204912/javascript-need-functions-to-convert-a-string-containing-binary-to-hex-then-co) or [*this*](http://stackoverflow.com/questions/7695450/how-to-program-hex2bin-in-javascript) help? [**This**](https://gist.github.com/faisalman/4213592) is my personal favourite! – Vikram Deshmukh Feb 17 '14 at 07:09
  • I searched for this 20 times using a bunch of different searches, couldn't find anything like that. OMG. – PitaJ Feb 17 '14 at 18:35

1 Answers1

2

Using built-in functions:

parseInt('1010101010', 2).toString(16)
epoch
  • 16,396
  • 4
  • 43
  • 71