簡體   English   中英

JAVA CRC16函數返回3個字符的響應,而不是4個字符

[英]JAVA CRC16 function returns a 3 characters response instead of 4

我有一個如下所示的Java CRC16函數,我需要它返回4個長度的字母數字結果。 但有時它僅返回3個長度的字母數字。 為什么? 我將這個CRC與計算CRC的C應用程序進行交叉比較,通常它是相同的CRC,但是JAVA有時會返回3個字符的結果,這會引發異常。 為什么?

int crrc = 0xFFFF;          // initial value
    int polynomial = 0x1021;   // 0001 0000 0010 0001  (0, 5, 12) 

    String str = "0009";

    byte []by = x; // x is the byte array from args
    for (byte b : by) {
        for (int i = 0; i < 8; i++) {
            boolean bit = ((b   >> (7-i) & 1) == 1);
            boolean c15 = ((crrc >> 15    & 1) == 1);
            crrc <<= 1;
            if (c15 ^ bit) crrc ^= polynomial;
         }
    }

    crrc &= 0xffff;
    System.out.println(crrc);
    System.out.println("CRC16-CCITT = " + Integer.toHexString(crrc) + " " + Integer.toHexString(crrc).length());

您可能正在接收ArrayIndexOutOfBoundException ,所以我認為十六進制值在其最重要的半字節中可能為零。 嘗試找出那些值( x )並檢查(x >>> 12) == 0還是(x & 0xf000) == 0 如果返回true,則可以從左側開始以0 s來填充字符串。

一種可能的方式: String.format("%04d", crrc)

暫無
暫無

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

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