Hexadecimal to float array converter

by seblavoie

HTML

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap-combined.min.css">
<h2>Hexadecimal to float array converter</h2>
<form class="form-inline" action="#">
    <label for="hexadecimal">Your hexadecimal value: </label> 
    <div class="input-prepend">
        <span class="add-on">#</span>
        <input class="js-hexadecimal-input" name="hexadecimal" type="text">
     </div>
    </form>
<p class="js-result"></p>

JavaScript

// Hexadecimal to float array converter
// Based on http://www.linuxtopia.org/online_books/javascript_guides/javascript_faq/hextorgb.htm
$(function(){
    $(".js-hexadecimal-input").focus();
    $(".js-hexadecimal-input").keyup(function() {
        var hex = cutHex($(this).val());
        $(".js-result").text("[" + convertHexToFloat(hex, 0, 2) + ", " + convertHexToFloat(hex, 2, 4) + ", " + convertHexToFloat(hex, 4, 6) + "]");
    });
    
    function convertHexToFloat(hex, limitMin, limitMax) {
        r = parseInt(hex.substring(limitMin, limitMax), 16);
        r = r / 255;
        r = Math.round(r*Math.pow(10,2))/Math.pow(10,2);
        return r;
    }
    
    function cutHex(h) {
        return (h.charAt(0)=="#") ? h.substring(1,7):h;
    }
})()