gpt4 book ai didi

javascript - 如何在 HTML5/javascript 中查找十六进制值的特定位或数字?

转载 作者:行者123 更新时间:2023-11-28 00:16:36 25 4
gpt4 key购买 nike

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

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 中也可用。

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

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

关于javascript - 如何在 HTML5/javascript 中查找十六进制值的特定位或数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11860514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com