簡體   English   中英

Java 中的校驗和

[英]Checksum in Java

所以我必須創建一個 class Fletcher16 並實現校驗和。 它必須包含4個方法:

  1. void update(int b):校驗和被更新為 b
  2. void update(byte[] b, int off, int len):校驗和使用數組 b 中的 len 值從 off 點開始更新。
  3. void reset():將校驗和設置為其初始值(在本例中為 0)
  4. void long getValue():返回校驗和的當前值。 為此 sum1 和 sum2 需要與方法 combineValues(int value1, int value2) 一起使用(這個已經完成)

我的問題:我到底應該怎么做? 我知道對於測試,我得到一個包含 1 個或 3 個 arguments 的數組。 如果是 3 arguments 那么 args[0] = m, args[1] = message, args[2] = checksum。 如果校驗和正確則返回 true,如果校驗和錯誤則返回 false。 如果它只是 1 個參數,則應該代表 m。 然后,您可以使用掃描儀從輸入中獲取消息。 在這種情況下,方法應該返回校驗和。

但是我該如何計算呢? 如何從字符串計算校驗和? 我們得到的定義是:

Fletcher16 (data)
Input: Array data of 8-Bit-Integer
Output: 16-Bit-Checksum to data

sum1 := 0
sum2 := 0

for i := 0 to length (data) do
    sum1 := (sum1 + data[i]) modulo M
    sum2 := (sum2 + sum1) modulo M
endfor

checksum := sum1 following sum2
return checksum

我也不太明白這 4 種方法應該是什么......有人可以給我一個提示嗎? 我當前的代碼幾乎是空的,但它是:

import java.util.Scanner;

import java.util.zip.Checksum;

public abstract class Fletcher16 implements Checksum {
    private static int sum1=0;
    private static int sum2=0;
    private static int m;
    
    public Fletcher16(int m){
        this.m = m;
    }
    public Fletcher16(){
        m = 255;
    public update(int b){
    }
    public update(byte[] b, int off, int len){
    }
    public reset()
    public long getValue()
    private static short combineValues(int value1, int value2) {
        return (short) ((value1 & 0x00ff) | ((value2 << 8) & 0xff00));

如果這看起來真的很奇怪或有一些非常糟糕的解釋,我很抱歉這是我第一次使用 stackoverflow:/ 提前致謝!

class 是一個完整的工作 class,因此不是abstract的。

public class Fletcher16 implements Checksum {

這些字段不是全局的,因此不是static

    private int sum1; // 0 per default.
    private int sum2;
    private int m;
    
    public Fletcher16(int m) {
        this.m = m;
    }

    public Fletcher16() {
        this(256); // Maybe 256 is better as default.
    }

兩種update方法似乎都是一個字節和幾個字節。

    @Override
    public update(int b) {
        ...
    }

    @Override
    public update(byte[] ba, int off, int len) {
        ... for ... update(ba[i]) ...

    }

重置意味着重新開始

    @Override
    public reset() {
        sum1 = 0;
        sum2 = 0;
    }

校驗和的getValue

    @Override
    public long getValue() ... // long?

並且不需要重復 combineValues 的定義; 只需在updategetValue中使用它。

public static void main(String[] args) {
    byte[] ba = args[0].getBytes(Charset.defaultCharset());
    if (args.length > 1) {
        int m = Integer.parseInt(args[1]);
        Checksum cs = new Fletcher16(m);
        cs.update(ba);
        cs. ...
    } else {
        ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM