Simulate an unsigned number with a specific power of two max in java

I have some output from a (C ++) application that stores the tickcount value in a type that wraps to zero at 2 33 . (8 589 934 592) (do not have a code)

I need to write my own output in the same way. I extract the checkmark from C lib via JNA, but if I store it in int, it wraps up to -2 31 (-2,147,483,648) after ~ 25 days mark and if I store it in long it just keeps going past 2 33 .

How can I save (or write) a value in Java so that it wraps (to zero) at 2 33 ?

(preferably JRE7- and JRE8- on Win32- and Win64- and Linux-compatible solutions)

To get a checkmark, I use the following:

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()); 
+6
source share
2 answers

You can store the value in long , and then truncate the value to 33 bits (wrap 2 33 around 0) by doing:

 n &= (1L << 33) - 1; 

This is exactly the same as:

 n &= 0x1_ffff_ffffL; 

which also matches:

 n &= 8_589_934_591L; 
+8
source

The simplest solution: you can do it in Java using a long one like

 long count; public void tick() { count++; count %= 8589934592L; } 
+5
source

All Articles