2

多くのものを16進数でエンコードしたいと思います。ここに例があります。

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

LAST_DIGITSとMID_DIGITSを一緒に追加したとしましょう。これは0x00000EA7で、エンコードしたい2つの異なるものを表しています。

javascript / HTML5で、そのサブセットを個別にチェックできる方法はありますか?または、それを文字列または他のコレクションに変換してから、インデックスを明示的に参照する必要がありますか?

上記の例では、これが私が探しているものです

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
}
4

1 に答える 1

2

一般的なビット演算子(| & >> <<など)もJavaScriptで使用できます。

その整数の16進表現から常に2桁の16進数字が必要であると仮定しましょう。そして、それらの数字のインデックスを左からではなく右から数えましょう。

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();
}

使用法:

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
于 2012-08-08T08:45:09.767 に答える