java,在十六进制数上设置位值

CMZ*_*MZS 0 java hex bit-manipulation

给定具有12位数字的任意十六进制数字,设置第n位数字值的最快方法是什么?例如,

0x100000000000
Run Code Online (Sandbox Code Playgroud)

如何将第10位数字设置为2,即102000000000。

检查Java文档后,我认为该数字可以在Java中定义为

int hex = 0x100000000000;
Run Code Online (Sandbox Code Playgroud)

我需要将其转换为0x102000000000。我尝试避免使用任何现有的类,例如BitSet,因为必须同时使用Java和纯JavaScript编写代码。谢谢

Dan*_*ore 5

这是我将使用按位运算符在Java中执行的操作。它在Javascript中应该非常相似。

public static void main(String[] args)
{
    long hex = 0x2222222222222222L;

    System.out.printf("0x%x", replaceDigit(hex, 10, 1));
}

public static long replaceDigit(long originalValue, int digitPosition, int replacementDigit)
{
    // Clear the 4 bits (i.e. 1 digit) at the position requested
    originalValue &= ~(0x0FL << digitPosition * 4);

    // Now put the replacement value at the position requested
    originalValue |= (long) replacementDigit << digitPosition * 4;

    return originalValue;
}
Run Code Online (Sandbox Code Playgroud)