我想为以下消息计算LRC:
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);
}
}
我得到的输出是不同的。我现在该怎么办?
答案 0 :(得分:4)
假设您正在谈论纵向冗余检查;如果有疑问,check you algorithm against published examples。
Here's one in Java,这似乎与你的完全不同。也许你的尝试是利用DeMorgan的理论来优化LRC,但是在这个过程中错误的可能性很大。
答案 1 :(得分: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);
答案 2 :(得分:0)
public static String lrc2hex (String str) {
byte[] bytes = str.getBytes ();
int lrc = 0;
for (int i = 0; i < str.length (); i++) {
lrc ^= (bytes[i] & 0xFF);
}
return String.format ("%02X ", lrc);
}
...
String data = "0200|666|0|0" + "\u0003"; // Includes a non-visible character
System.out.println ("DATA: " + data); // DATA: 0200|666|0|0
System.out.println ("LRC: " + lrc2hex (data)); // LRC: 4B
运行演示:https://www.jdoodle.com/a/qWQ
更多信息:https://asecuritysite.com/calculators/lrc?a=0200|666|0|0%03
答案 3 :(得分:0)
它对我有用。
public static byte CalcLRC(byte[] bytes) {
byte LRC = 0x00;
for (byte aByte : bytes) {
LRC = (byte) ((LRC + aByte) & 0xFF);
}
return (byte)(((LRC ^ 0xFF) + 1) & 0xFF);
}