从另一个号码获取一个不太具体的号码

时间:2012-08-22 07:30:44

标签: java math numbers bit-manipulation

是的,对不起,我想不出谷歌这个正确的话。所以我不得不问。

我有longSystem.currentTimeMillis()

让我们说

3453646345345345

我想删除最后六位(或其他数字)的数字,我想我可以做一些这样的位移?

所以我最终会以

结束

3453646345

修改

我想在一个时间框内得到System.currentTimeMillis(),所以如果我要求时间,那么在29秒后再次询问它将返回相同的数字,但如果我问31秒后它将返回不同的数字。 30秒的时间框是可配置的。

3 个答案:

答案 0 :(得分:6)

您必须将其除以1M long shorter = System.currentTimeMillis() / 1000000L;

答案 1 :(得分:3)

要建立@ Yob的答案,您可以通过创建如下方法来设置要删除的位数:

public long removeDigits(long number, int digitsToRemove) {
    return number / (long)Math.pow(10, digitsToRemove);
}

答案 2 :(得分:1)

根据你想要做的事情(在基数10中,我假设),你可以这样做:

int64_t radix = 1000000; // or some other power of 10

x -= x%radix; // last 6 decimal digits are now 0
              // e.g: from 3453646345345345 to 3453646345000000

或者这(如上一个答案):

x /= radix; // last 6 decimal digits are gone, the result rounded down
            // e.g: from 3453646345345345 to 3453646345

对编辑的响应

出于您的目的,您可以将模数示例中的radix更改为30000:

int64_t timeInterval = 30000;
displayTime = actualTime - (actualTime % timeInterval);

其中displayTimeactualTime属于毫秒级。在这种情况下,displayTime将具有30秒的(向下舍入)粒度,同时保持毫秒单位。

要获得舍入的粒度,您可以执行以下操作:

int64_t timeInterval = 30000;
int64_t modulus = actualTime % timeInterval;
displayTime = actualTime - modulus + (modulus?timeInterval:0);

虽然根据您的要求,您似乎只想每隔几个滴答更新显示值。以下内容也适用:

if((actualTime - displayTime) >= timeInterval){
    displayTime = actualTime - (actualTime % timeInterval);
}

请原谅C整数类型,我更喜欢明确我正在使用的整数宽度:P。