且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中的8位Fletcher算法的正确实现是什么?

更新时间:2022-12-04 12:57:23

根据本文,您应该对ckA和ckB的值执行模数计算,以防止它们超过255。因此示例如下:

 字符串bin = 100100101011111011101011; 
char [] cA = bin.toCharArray();
int ckA = 0,ckB = 0;
for(int i = 0; i< cA.length; i ++){
ckA =(ckA + Integer.valueOf(cA [i])/ 49)%255;
ckB =(ckB + ckA)%255;
}
System.out.println(ckA);
System.out.println(ckB);

System.out.println((ckB<< 8)| ckA);

这可能主要是由于最终校验和是8位移位的ckB OR与ckA,因此ckA的值几乎肯定应该小于256。但是,除非您处理的是可能很大的二进制字符串,否则您可能只能在ckA上执行模数计算。


i am trying to implement the 8-bit fletcher algorithm. I wrote a piece of code that does that but i am not sure if i understood the algorithm correctly. this is my piece of code:

public class TestFletcher {
public static void main(String[] argv) {

    String bin = "10010010101111101110101101110011";
    char[] cA = bin.toCharArray();
    int ckA = 0, ckB = 0;
    for (int i = 0; i < cA.length; i++){
        ckA += Integer.valueOf(cA[i])/49;
        ckB += ckA;
    }
    System.out.println(ckA);
    System.out.println(ckB);

}

the results that i am getting are : ckA = 20, ckB = 308. i assume this is not the correct implementation since 308 can not be represented by an 8bit binary which is the length of ckA and ckB.

can any one shed some light on this problem? any help would be appreciated. thank you.

According to this article, you should be performing modulus calculation on the values of ckA and ckB to prevent them from exceeding 255. So the example would be:

String bin = "100100101011111011101011";
char[] cA = bin.toCharArray();
int ckA = 0, ckB = 0;
for (int i = 0; i < cA.length; i++){
    ckA = (ckA + Integer.valueOf(cA[i])/49) % 255;
    ckB = (ckB + ckA) % 255;
}
System.out.println(ckA);
System.out.println(ckB);

System.out.println((ckB << 8) | ckA);

This is probably mostly due to the fact that the end checksum is a 8-bit shifted ckB ORed with ckA, and so the value of ckA should almost certainly be less than 256. However unless you're dealing with potentially large binary strings, you could probably get away with performing the modulus calculation only on ckA.