转载于:https://blog.csdn.net/Dimpies/article/details/104024002
import java.util.ArrayList;
public class AffineDecode {
public static void main(String[] args) {
String Qr_Str="3A56B45C5D52EF45451G";
System.out.println("待处理的字符串:"+Qr_Str);
String Affine=Affine_Str(Qr_Str);//提取明文信息
int[] key=key(Qr_Str);//提取密钥
Affine_Code(Affine,key);//提取红外码
}
public static String Affine_Str(String Qr_Str) {
char[] chars=Qr_Str.toCharArray();
char[] Str_a=new char[7];
int str_index=0;
ArrayList<Integer> array=new ArrayList<Integer>();//定义动态数组
for(int i=0;i<Qr_Str.length();i++) {
if((chars[i]>='A'&&chars[i]<='Z')) {
Str_a[str_index]=chars[i];
str_index++;
if(str_index==8) {
break;
}
}
}
String Affine_a=new String(Str_a);
System.out.print("提取的明文信息:"+Affine_a);
System.out.println();
return Affine_a;
}
public static int[] key(String Qr_Str) {
char[] chars=Qr_Str.toCharArray();
ArrayList<Integer> array=new ArrayList<Integer>();
int[] key=new int[2];
for(int i=0;i<Qr_Str.length();i++) {
if((chars[i]>='0'&&chars[i]<='9')) {
int num=(chars[i]-'0');
array.add(num);
}
}
System.out.print("提取出来的数字:");
for(int n:array) {
System.out.print(n);
}
key[0]=array.get(0);
key[1]=array.get(array.size()-1);
System.out.println();
System.out.format("密钥: K=(%d,%d)",key[0],key[1]);
return key;
}
public static int[] Affine_Code(String Affine,int[] key) {
int[] infrared_coder=new int[6];
int k3=((26+1)/key[0]);//(K3*K1)%26=1;K1=3,求最小模逆K3=(1+26(n))/3(K1)
int k2=key[1];
char[] Affine_AZ=Affine.toCharArray();
char[] Affine_az=new char[7];
// Affine_az[0]=(char) ((k3*((Affine_AZ[i]-'A')-k2)%26)+'a');
for(int i=0;i<7;i++) {
if((Affine_AZ[i]-'A')<k2) {
Affine_az[i]=(char)((k3*((Affine_AZ[i]-'A')-k2)%26+26)+'a');
}else {
Affine_az[i]=(char)((k3*((Affine_AZ[i]-'A')-k2)%26)+'a');
}
}
for(int i=0;i<6;i++) {
if(i%2==0) {
infrared_coder[i]=Math.abs(Affine_az[i+1]-Affine_az[i]);
}
else {
infrared_coder[i]=Math.abs(Affine_az[i+1]+Affine_az[i]);
}
}
System.out.println();
// System.out.println(Affine_az[0]);
for(char n:Affine_az) {
System.out.print(n);
}
System.out.println();
System.out.print("红外码:");
for(int n:infrared_coder) {
System.out.print(Integer.toHexString(n)+" ");
}
return infrared_coder;//返回红外码
}
}