C++ to Java and unsigned int64?

Hi all,

Can this code snippet be converted to Java?


u64 magic_table[24] = {
  0x1000000010000000ull,
  0x1000000000010000ull,
  0x1000000000000001ull,
  0x0100000001000000ull,
  0x0100000000010000ull,
  0x0100000000000010ull,
  0x0010000000100000ull,
  0x0010000000010000ull,
  0x0010000000000100ull,
  0x0001000010000000ull,
  0x0001000001000000ull,
  0x0001000000100000ull,
  0x0000100000000100ull,
  0x0000100000000010ull,
  0x0000100000000001ull,
  0x0000010000100000ull,
  0x0000010000001000ull,
  0x0000010000000100ull,
  0x0000001001000000ull,
  0x0000001000001000ull,
  0x0000001000000010ull,
  0x0000000110000000ull,
  0x0000000100001000ull,
  0x0000000100000001ull
};

u64 test(u64 magic_sum, int square) {
  u64 before = magic_sum & 0x4444444444444444ull;
  u64 afte = (magic_sum + magic_table[square]) & 0x4444444444444444ull;
  return after & ~before;
}

Change: u64 to long. change: ull to L.

I’ve already tried that approach but the function returns just long which I can’t use instead of the bits.

What do you mean you can’t use it? The C version returns a u64, which is just a “long” in Java (though Java’s is signed)

Cas :slight_smile:

It would be helpful if you gave an example of what you’re not understanding how to do.

This won’t work in java as there is no unsigned 64 bit integer. Using a regular signed long would usually work fine but you are doing addition and using all 64 bits which includes the sign bit. You could use java BigInteger but it will be slow and I suspect this is purely a performance hack so I suggest you just replace it with whatever you are actually trying to do.

There’s no difference between signed and unsigned addition in 2’s complement.

Java just wraps over int’s and long’s, so it is irrelevant. Bitwise it is irrelevant if its signed or unsigned, the addition works the same way (the CPU doesn’t care if you consider a value as signed or unsigned). The only time when attention must be paid when porting code that deals with unsigned types is the right-shift operator “>>”. If the original code works with unsigned types, then the unsigned-shift “>>>” must be used. The “>>” preserves the sign (the top bit), while the unsigned shift “>>>” shifts in a 0 to the topmost bit. But addition and subtraction works the same.