【问题标题】:How do I look up the particular bits or digits of a hex value in HTML5 / javascript?如何在 HTML5 / javascript 中查找十六进制值的特定位或数字?
【发布时间】:2012-08-08 08:24:17
【问题描述】:

我想用十六进制编码很多东西。以下是示例。

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,代表我要编码的两种不同的东西。

有什么方法可以让我在 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
}

【问题讨论】:

    标签: javascript html hex


    【解决方案1】:

    常见的位运算符(| & >> << 等)也可用于 JavaScript。

    让我们假设您总是需要该整数的十六进制表示中的两个十六进制数字。让我们从右边而不是从左边计算这些数字的索引:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      相关资源
      最近更新 更多