2011-06-03 121 views
0

我想要計算LRC爲以下消息:計算LRC在Java

 
T = 0101 0100 
P = 0101 0000 
1 = 0011 0001 
2 = 0011 0010 


Starting with 0x00 as the initial byte. 

0 XOR ‘T’:   0000 0000 
0101 0100 
Result, LRC = 0101 0100 


LRC XOR ‘P’: 0101 0100 
         0101 0000 
Result, LRC = 0000 0100 


LRC XOR ‘1’: 0000 0100 
         0011 0001 
Result, LRC = 0011 0101 


LRC XOR ‘2’: 0011 0101 
         0011 0010 
Result, LRC = 0000 0111

到目前爲止我已經嘗試的代碼如下所示:

public class TexttoBinary { 

private static final int maxBytes = 1; 

public static int convert(char number) { 

    // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.print("Type the number to parse: "); 
    //int number = Integer.parseInt(in.readLine()); 
    int Bit; 
    //char number = '1'; 
    //UInt8 i; 
    String result = ""; 
    for (int i = maxBytes * 7; i >=0; i--) { 
     Bit = 1 << i; 
     if (number >= Bit) { 
      result += 1; 
      //System.out.println(result); 
      number -= Bit; 
     } else { 
      result += 0; 
     } 
    } 
    System.out.println(result); 
    return Integer.parseInt(result); 
} 
public static void main(String args[]){ 
    String msg ="TP12"; 
    char[] toCharArray = msg.toCharArray(); 
    char lrc=0; 
    for(int i=0;i<toCharArray.length;i++) 
    lrc ^=convert(toCharArray[i]); 
    System.out.println((byte)lrc); 
} 

}

輸出I我越來越不同了。現在我該怎麼做 ?

+2

什麼是「LRC」? – dkamins 2011-06-03 00:39:06

+1

你現在要做的是調試你的代碼。 – 2011-06-03 00:40:42

+0

@dkamins:LRC是縱向冗餘檢查 – Deepak 2011-06-03 00:43:12

回答

4

假設你在談論縱向冗餘檢查;當有疑問時,check you algorithm against published examples

Here's one in Java,這看起來與你的完全不同。也許你的嘗試是利用德摩根的規範來優化LRC,但是很可能它會帶來一個錯誤。

+0

但這並沒有給我8位LRC。我怎麼得到8位LRC從達? – Deepak 2011-06-03 00:55:50

+0

我越來越97 7 – Deepak 2011-06-03 00:56:55

+0

@Deepak,一個字節被定義爲8位,異或操作位清,所以對兩個字節進行異或運算與循環和異或一個字節完全相同 – 2011-06-03 03:15:23

0

以下代碼在java中爲我工作,用於驗證信用卡磁條讀取。 see it running online here.

String str = ";4564456445644564=1012101123456789?"; 
byte lrc = 0x00; 
byte [] binaryValue = str.getBytes(); 

for(byte b : binaryValue) { 

    lrc ^= b; 
} 

// lrc msut be between 48 to 95 
lrc %= 48; 
lrc += 48; 

System.out.println("LRC: " + (char) lrc);