繁体   English   中英

大uint64_t从C到Java的模划分

[英]Modulo division of large uint64_t from C to Java

因此,这是一个我希望能够在Java中重现的简单C程序:

#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);
}

编译为: gcc -Wall -std=c11 main.c 我的gcc --version7.1.1 20170621

到目前为止,我已经尝试过了:

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)
            );
    }
}

编译为: javac Main.c ,我的javac -version1.8.0_131并且我假设它产生Java 8。

但是,如您所见,结果是不同的。 C可执行文件给您2作为模,而Java根据您使用的模给您-4或1。 我在这里做错了什么?

好吧,对我来说答案是Long.remainderUnsigned ,这是自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));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM