在 java 中模拟具有两个最大幂的无符号数
Simulating unsigned number with a certain power of two max in java
我有一些来自 (C++) 应用程序的输出,该应用程序将 tickcount 值存储在一种类型中,该类型在 233 处回绕为零。 (8,589,934,592) (没有密码)
我需要以同样的方式编写自己的输出。我通过 JNA 从 C lib 中检索了 tickcount,但是如果我将它存储在一个 int 中,它会在 ~25 天的 tickcount 之后换行到 -231 (-2,147,483,648) 如果我存储它在很长一段时间内,它一直超过 233。
如何存储(或写入)Java 中的值,使其在 233 处回绕(归零)?
(最好是在 Win32 和 Win64 上的 JRE7 和 JRE8 以及 Linux 兼容的解决方案)
要获取滴答计数,我使用以下命令:
import com.sun.jna.*;
public interface Kernel32 extends Library {
Kernel32 INSTANCE = (Kernel32) Native.loadLibrary((Platform.isWindows() ? "kernel32" : "c"), Kernel32.class);
/**
* Retrieves the number of milliseconds that have elapsed since the system was started.
*
* @return number of milliseconds that have elapsed since the system was started.
* @see http://msdn2.microsoft.com/en-us/library/ms724408.aspx
*/
Long GetTickCount();
}
public interface Clib extends Library {
Clib INSTANCE = (Clib) Native.loadLibrary((Platform.isWindows() ? "kernel32" : "c"), Clib.class);
/**
* Retrieves the number of milliseconds that have elapsed since the system was started.
*
* @return number of milliseconds that have elapsed since the system was started.
*/
Long clock();
}
// And later
Number n = (Platform.isWindows() ? Kernel32.INSTANCE.GetTickCount() : Clib.INSTANCE.clock()).toString());
您可以将值存储在 long
中,然后通过执行以下操作将值截断为 33 位(将 233 环绕为 0):
n &= (1L << 33) - 1;
这与:
完全相同
n &= 0x1_ffff_ffffL;
也等同于:
n &= 8_589_934_591L;
最简单的解决方案:您可以在 Java 中使用 long,例如
long count;
public void tick() {
count++;
count %= 8589934592L;
}
我有一些来自 (C++) 应用程序的输出,该应用程序将 tickcount 值存储在一种类型中,该类型在 233 处回绕为零。 (8,589,934,592) (没有密码)
我需要以同样的方式编写自己的输出。我通过 JNA 从 C lib 中检索了 tickcount,但是如果我将它存储在一个 int 中,它会在 ~25 天的 tickcount 之后换行到 -231 (-2,147,483,648) 如果我存储它在很长一段时间内,它一直超过 233。
如何存储(或写入)Java 中的值,使其在 233 处回绕(归零)?
(最好是在 Win32 和 Win64 上的 JRE7 和 JRE8 以及 Linux 兼容的解决方案)
要获取滴答计数,我使用以下命令:
import com.sun.jna.*;
public interface Kernel32 extends Library {
Kernel32 INSTANCE = (Kernel32) Native.loadLibrary((Platform.isWindows() ? "kernel32" : "c"), Kernel32.class);
/**
* Retrieves the number of milliseconds that have elapsed since the system was started.
*
* @return number of milliseconds that have elapsed since the system was started.
* @see http://msdn2.microsoft.com/en-us/library/ms724408.aspx
*/
Long GetTickCount();
}
public interface Clib extends Library {
Clib INSTANCE = (Clib) Native.loadLibrary((Platform.isWindows() ? "kernel32" : "c"), Clib.class);
/**
* Retrieves the number of milliseconds that have elapsed since the system was started.
*
* @return number of milliseconds that have elapsed since the system was started.
*/
Long clock();
}
// And later
Number n = (Platform.isWindows() ? Kernel32.INSTANCE.GetTickCount() : Clib.INSTANCE.clock()).toString());
您可以将值存储在 long
中,然后通过执行以下操作将值截断为 33 位(将 233 环绕为 0):
n &= (1L << 33) - 1;
这与:
完全相同n &= 0x1_ffff_ffffL;
也等同于:
n &= 8_589_934_591L;
最简单的解决方案:您可以在 Java 中使用 long,例如
long count;
public void tick() {
count++;
count %= 8589934592L;
}