8

Java 中是否有任何库/代码可以以与 unix 中的 cksum 命令一致的方式计算字节流的 32 位 CRC?

4

3 回答 3

6

Jacksum:http ://www.jonelo.de/java/jacksum/index.html

cksum         algorithm:   POSIX 1003.2 CRC algorithm
              length:      32 bits
              type:        crc
              since:       Jacksum 1.0.0
              comment:     - under BeOS    it is /bin/cksum
                           - under FreeBSD it is /usr/bin/cksum
                           - under HP-UX   it is /usr/bin/cksum and
                             /usr/bin/sum -p
                           - under IBM AIX it is /usr/bin/cksum
                           - under Linux   it is /usr/bin/cksum 

它是具有 GPL 许可的开源软件。

于 2011-10-12T21:54:21.557 回答
2

您是否尝试过 CRC32 课程?

http://download.oracle.com/javase/7/docs/api/java/util/zip/CRC32.html

这是 gzip 使用的 crc 32。

于 2011-10-12T21:00:10.410 回答
1

正如@RobertTupelo-Schneck 指出的那样, MacOS 上的cksum命令允许选择历史算法,算法 3 与 相同。java.util.zip.CRC32出于某种原因,更紧凑会CheckedInputStream产生不同的校验和。

例如

$ cksum -o 3 /bin/ls
4187574503 38704 /bin/ls

如同 :

package com.elsevier.hmsearch.util;
import static java.lang.System.out;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;

public class Demo {

  static final String FILE = "/bin/ls";
  
  public static void main(String[] args) throws Exception {
    Checksum cs = new CRC32();
    byte[] buffer = new byte[4096];
    long totalBytes = 0;
    
    InputStream is = Files.newInputStream(Paths.get(FILE));
    int bytesRead = is.read(buffer);
    totalBytes += bytesRead;
    //CheckedInputStream checkedInputStream = new CheckedInputStream(is, new CRC32());
    //while ((bytesRead = checkedInputStream.read(buffer, 0, buffer.length)) >= 0) {
    //  totalBytes += bytesRead;
    //}
    while (bytesRead > 0) {
      cs.update(buffer, 0, bytesRead);
      bytesRead = is.read(buffer);
      if (bytesRead < 1)
        break;
      totalBytes += bytesRead;
    }
    //out.printf("%d %d %s\n", checkedInputStream.getChecksum().getValue(), totalBytes, FILE);
    out.printf("%d %d %s\n", cs.getValue(), totalBytes, FILE);
  }
}
于 2021-09-23T23:59:04.523 回答