开发者

What would be the most performant (also safe) way to replace the last digit of a long?

开发者 https://www.devze.com 2023-02-15 06:03 出处:网络
What would be the most performan开发者_运维问答t (also safe) way to replace the last digit(Least significant digit) of a long(that was actually generated as timestamp by System.currentTimeInMillis())

What would be the most performan开发者_运维问答t (also safe) way to replace the last digit(Least significant digit) of a long(that was actually generated as timestamp by System.currentTimeInMillis()) by some other digit?

Or is there a better way to attach any fixed attachment to the end of it, by making use of bitwise operations?


In your comments you say that both binary digits or decimal digits would be fine. Since Andrew posted the decimal version, i post the binary version in which you want to replace the 2 ls-bits:

The following program goes through the 4 possibilities with which you can replace the 2 ls-bits and produces the output:

9999999999999999
9999999999999996
9999999999999997
9999999999999998
9999999999999999

code:

public class A {
public static void main(String[] args) {

    long aLong = 9999999999999999L;
    System.out.println(aLong);

    long aLong2 = aLong & ~3 + 0;
    System.out.println(aLong2);
    aLong2 = aLong & ~3 + 1;
    System.out.println(aLong2);
    aLong2 = aLong & ~3 + 2;
    System.out.println(aLong2);
    aLong2 = aLong & ~3 + 3;
    System.out.println(aLong2);


}
}


If this is not a hypothetical question, ie to find a fast algorithm for the heck of it, then please ignore this answer. The correct way (as has been mentioned) is to do (somelong/10)*10 + newvalue

A faster (hypothetical) way is probably to have some two dimension array of adjustment values.

int[][] adjustment = new int[16][10];

where the first array index represents what the current value is anded with 0x0F (the last 4 bits) the second array index would be what you want the new number to be

the value is the adjustment to the variable

so the code would be

newLong = somelong + adjustment[somelong&0x0F][what_you_want_the_new_digit];

so no multiplication or division

as an example, let's say the input number is 22, and you want it to be 26

26 is 011010 so 26 & 0x0F is the bottom 4 bits 1010 which is 10

adjustment[10][6] = 4 (you have precalculated that it is 4)

so you'd have 22 + 4 = 26

obviously index 10 is the same as index 0, index 11, is the same as index 1, etc, etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消