So, here is a simple C program that I would like to be able to reproduce in Java:
#include<stdio.h>
#include<stdint.h>
int main() {
uint64_t x = 0xB3E110C4CFF34548;
printf("%16lX %20ld\n", x, x);
printf("%16lX %20ld\n", x % 5, x % 5);
}
Compile with: gcc -Wall -std=c11 main.c
. My gcc --version
is 7.1.1 20170621
So far, I have tried this:
public class Main {
public static void main(String[] args) {
long x = 0xB3E110C4CFF34548L;
System.out.printf("%16X %20d\n", x, x);
System.out.printf("%16X %20d\n", x % 5, x % 5);
System.out.printf(
"%16X %20d\n", Math.floorMod(x, 5), Math.floorMod(x, 5)
);
}
}
Compile with: javac Main.c
, my javac -version
is 1.8.0_131
and I assume it produces Java 8.
However, as you can see for yourself, the results are different. C executable gives you 2 as modulo, while Java gives you -4 or 1 depending on the modulo you use. What am I doing wrong here?
Alright, for me the answer turned out to be Long.remainderUnsigned
which is a new feature since Java 8:
public class Main {
public static void main(String[] args) {
long x = 0xB3E110C4CFF34548L;
System.out.printf("%16X %20d\n", x, x);
System.out.printf("%16X %20d\n", x % 5, x % 5);
System.out.printf(
"%16X %20d\n", Math.floorMod(x, 5), Math.floorMod(x, 5)
);
System.out.printf("%16X %20d\n", Long.remainderUnsigned(x, 5), Long.remainderUnsigned(x, 5));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.