what is the correct implementation of the 8-bit Fletcher algorithm in java?

一世执手 提交于 2020-01-24 10:04:01

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/35886276/what-is-the-correct-implementation-of-the-8-bit-fletcher-algorithm-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!