How do I look up the particular bits or digits of a hex value in HTML5 / javascript?

2

I want to encode many things in hex. Here are examples.

var LAST_DIGITS = 0x000000A7; // Last 2 digits represent something
var MID_DIGITS = 0x00000E00;  // 5th and 6th digits represent something else

Let's say I added LAST_DIGITS and MID_DIGITS together. That's 0x00000EA7 and represents the two different things I want to encode.

Is there some way I can just check a subset of that independently, in javascript/HTML5? Or do I have to turn it into a string or other collection and then reference indices explicitly?

In the above example, here's what I'm looking for

function getThemDigits (inHexValue) 
{
    // Check for 5th and 6th digits through my dream (not real!) function
    inHexValue.fakeGetHexValueFunction(4,5); // returns 0E

    // Check for last two digits for something else
    inHexValue.fakeGetHexValueFunction(6,7); // returns A7
}
javascript
html
hex
asked on Stack Overflow Aug 8, 2012 by Danny

1 Answer

2

The common Bit-Operators (| & >> << etc.) are also available in JavaScript.

Lets assume that you always want two hexadecimal digits from the hexadecimal representation of that integer. And lets count the index of those digits from the right rather than from the left:

function GetHex(hex, offset) {
    // Move the two hex-digits to the very right (1 hex = 4 bit)
    var aligned = hex >> (4 * offset);

    // Strip away the stuff that might still be to the left of the
    // targeted bits:
    var stripped = aligned & 0xFF;

    // Transform the integer to a string (in hex representation)
    var result = stripped.toString(16);

    // Add an extra zero to ensure that the result will always be two chars long
    if (result.length < 2) {
        result = "0" + result;
    }

    // Return as uppercase, for cosmetic reasons
    return result.toUpperCase();
}

Usage:

var LAST_DIGITS = 0x000000A7;
var MID_DIGITS = 0x00000E00;

var a = GetHex(LAST_DIGITS, 0);
var b = GetHex(MID_DIGITS, 2); // offset of 2 hex-digits, looking from the right
answered on Stack Overflow Aug 8, 2012 by Niko

User contributions licensed under CC BY-SA 3.0