gpt4 book ai didi

javascript - 在javascript中从头到尾提取位

转载 作者:行者123 更新时间:2023-12-02 16:22:14 25 4
gpt4 key购买 nike

在 Java 脚本中,我想从整数中提取第 13 到 16 位。示例:如果我从数字 16640 中提取位 13 到 16,则输出将为 2

我在谷歌上搜索过,发现很少links但它们是C语言的。

最佳答案

假设您的位数从 0 开始:

var extracted, orig;

orig = parseInt("16640", 10); // best practice on using parseInt: specify number base to avoid spurious octal interpretation on leading zeroes (thx Ken Fyrstenberg)
extracted = ((orig & ((1 << 16) - 1) & ~(((1 << 13) - 1))) >>> 13);

说明:

  • 屏蔽原始数字的低 16 位
  • 屏蔽结果低 13 位的补码(即位 13-31)
  • 当前,原始数字的第 13-16 位位于其原始位置。将此位模式向右移动 13 位。

请注意,此方法仅适用于小于 2^31 的数字。文档 (MDN) 是 here

关于javascript - 在javascript中从头到尾提取位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29011233/

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