Monday, 13 March 2017

Convert hex number to string of binary to then substring it

I need to convert a hex number to binary, then i need to substring the first 4 binary bits and convert that to decimal, I am not sure how to go about this I have found this little function but I don't really understand what it returns.

function hex2bin(hex)
{
    var bytes = [], str;

    for(var i=0; i< hex.length-1; i+=2)
        bytes.push(parseInt(hex.substr(i, 2), 16));

    return String.fromCharCode.apply(String, bytes);
}

Example:

  • hex: 0C

  • binary: [00001100]

I need the numbers in bold to be converted in decimal.



via Rémi

No comments:

Post a Comment