CMZS
CMZS

Reputation: 601

java, set bit values on hex number

Given an arbitrary hex number which has 12 digits, what is the fastest way to set the n-th digit value? For example,

0x100000000000

how to set the 10th digit to 2, that is, 102000000000.

After checking the java doc, I think the number can be defined in java as

int hex = 0x100000000000;

and I need to convert it to 0x102000000000. I try to avoid to use any existing classes such as BitSet, since the code has to be written in both java and plain javascript. Thanks

Upvotes: 1

Views: 1177

Answers (1)

Daniel Centore
Daniel Centore

Reputation: 3349

Here is how I would do it in Java using bitwise operators. It should be very similar in 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;
}

Upvotes: 5

Related Questions