Java 将4个字母转换为特定的二进制数字如何将这些二进制转换为ASCII int re=0; 对于(int t=0;t

Java 将4个字母转换为特定的二进制数字如何将这些二进制转换为ASCII int re=0; 对于(int t=0;t,java,netbeans,Java,Netbeans,Sam,您需要创建某种翻译表,以便知道哪个临时二进制位与哪个字符相关,我说是临时的,因为00与字母“A”完全不同在二进制中。这同样适用于您提供的其他字符的二进制表示形式。二进制表示形式可能与此无关,因为您可以为特定目的执行任何操作。但是,如果可能,正确的表示形式是以后实现更高级功能的方法ND您不需要翻译表,因为您只需将字符ASCII值转换为二进制,如下所示: int re = 0; for (int t=0; t<mat1.length-1; t++){ if(mat1[t]=="

Sam,您需要创建某种翻译表,以便知道哪个临时二进制位与哪个字符相关,我说是临时的,因为00与字母“A”完全不同在二进制中。这同样适用于您提供的其他字符的二进制表示形式。二进制表示形式可能与此无关,因为您可以为特定目的执行任何操作。但是,如果可能,正确的表示形式是以后实现更高级功能的方法ND您不需要翻译表,因为您只需将字符ASCII值转换为二进制,如下所示:

int re = 0;
for (int t=0; t<mat1.length-1; t++){
    if(mat1[t]=="A"){
        re=re+00;
    }else if(mat1[t]=="T"){
        re=re+01;
    }else if(mat1[t]=="G"){
        re=re+10;
    }else if(mat1[t]=="C"){
        re=re+11;
    }

    System.out.println(mat1[t]);
}
import java.util.Arrays;
import java.util.Scanner;

public class CharacterTranslation {

    public static void main(String[] args) {
        // Get Input from User...
        Scanner in = new Scanner (System.in);
        System.out.println("***  CONVERT FROM STRING TO ASCII TO BINARY TO ACGT  ***\n");
        System.out.println("Please enter a String to Convert to ACGT:");
        String inputString = in.nextLine();   

        // Declare and initialize required variables...
        int[] inputAscii = new int[inputString.length()];
        String[] inputBinary = new String[inputString.length()];
        // Translation Table made from a two dimensional Array:
        String[][] ACGTtranslation = {{"A","00"},{"T","01"},{"G","10"},{"C","11"}};

        // ------------------------------------------------
        // --------  CONVERT FROM STRING TO ACGT ----------
        // ------------------------------------------------

        //Convert the input string into ASCII numbers...
        for (int i = 0; i < inputString.length(); i++) {
            char character = inputString.charAt(i); 
            inputAscii[i] = (int) character; 
        }

        System.out.println("Conversion To ASCII:  " + Arrays.toString(inputAscii)
                           .replace("[","").replace("]",""));

        //Convert the ASCII Numbers to 8 bit Binary numbers...
        for (int i = 0; i < inputAscii.length; i++) {
            String bs =  String.valueOf(Integer.toBinaryString(0x100 + 
                         inputAscii[i]).substring(2));
            // Pad the left end of the binary number with 0 should
            // it not be 8 bits. ASCII Charcters will only produce
            // 7 bit binary. We must have 8 bits to acquire a even
            // number of digit pairs for our ACGT convertion.
            while (bs.length() < 8) { bs = "0" + bs; }
            inputBinary[i] = bs; 
        }

        System.out.println("Conversion To 8bit Binary:  " + Arrays.toString(inputBinary)
                           .replace("[","").replace("]",""));

        //Convert the Binary String to ACGT format based from 
        // our translational Two Dimensional String Array.
        // First we append all the binary data together to form
        // a single string of binary numbers then starting from 
        // the left we break off 2 binary digits at a time to 
        // convert to our ACGT string format.

        // Convert the inputBinary Array to a single binary String...
        String binaryString = "";
        for (int i = 0; i < inputBinary.length; i++) {
            binaryString+= String.valueOf(inputBinary[i]);
        }
        // Convert the Binary String to ACGT...
        String ACGTstring = "";
        for (int i = 0; i < binaryString.length(); i+= 2) {
            String tmp = binaryString.substring(i, i+2);
            for (int j = 0; j < ACGTtranslation.length; j++) {
                if (tmp.equals(ACGTtranslation[j][1])) { 
                    ACGTstring+= ACGTtranslation[j][0];
                }            
            }
        }

        System.out.println("The ACGT Translation String for the Word '" +
                           inputString + "' is:  " + ACGTstring + "\n");


        // ------------------------------------------------
        // -----  CONVERT FROM ACGT BACK TO STRING --------
        // ------------------------------------------------

        System.out.println("***  CONVERT FROM ACGT (" + ACGTstring + 
                           "' TO BINARY TO ASCII TO STRING  ***\n");
        System.out.println("Press ENTER Key To Continue...");
        String tmp = in.nextLine();

        // Convert ACGT back to 8bit Binary...

        String translation = "";
        for (int i = 0; i < ACGTstring.length(); i++) {
            String c = Character.toString(ACGTstring.charAt(i)); 
            for (int j = 0; j < ACGTtranslation.length; j++) {
                if (ACGTtranslation[j][0].equals(c)) { translation+= ACGTtranslation[j][1]; break; }
            }
        }

        // We divide the translation String by 8 so as to get 
        // the total number of 8 bit binary numbers that would
        // be contained within that ACGT String. We then reinitialize
        // our inputBinary Array to hold that many binary numbers.
        inputBinary = new String[translation.length() / 8];
        int cntr = 0;
        for (int i = 0; i < translation.length(); i+= 8) {
            inputBinary[cntr] = translation.substring(i, i+8);
            cntr++;
        }
        System.out.println("Conversion from ACGT To 8bit Binary:  " + 
                           Arrays.toString(inputBinary).replace("[","")
                           .replace("]",""));

        //Convert 8bit Binary To ASCII...
        inputAscii = new int[inputBinary.length];
        for (int i = 0; i < inputBinary.length; i++) {
            inputAscii[i] = Integer.parseInt(inputBinary[i], 2);
        }

        System.out.println("Conversion from Binary To ASCII:  " + Arrays.toString(inputAscii)
                           .replace("[","").replace("]",""));

        // Convert ASCII to Character String...
        inputString = "";
        for (int i = 0; i < inputAscii.length; i++) {
            inputString+= Character.toString ((char) inputAscii[i]);
        }

        System.out.println("Conversion from ASCII to Character String:  " + inputString);
        System.out.println("**  Process Complete  ***");
    }
} 
您已经有一个名为mat1[]的数组变量其中包含字符串字母,我建议将其设置为二维数组,1列用于保存字母,第2列用于保存该字母的二进制翻译。一旦建立了翻译,您可以来回转换字母字符串到二进制以及二进制到字母字符串。下面是代码(只需复制/粘贴并运行):

公共类字符翻译{
公共静态void main(字符串[]args){
//由二维数组构成的转换表:
字符串[][]mat1={{“A”,“00”},{“T”,“01”},{“G”,“10”},{“C”,“11”};
字符串输入=“GCAT”;
System.out.println(“原始输入:”+输入);
//转换提供的输入字符串中的每个字符
//我们的二进制字符翻译。
字符串翻译=”;
对于(int i=0;i
根据您上次的评论Sam,我相信我现在了解了您的要求,正如您在下面的代码中所看到的,只要遵循特定的规则,就相对容易完成

一个这样的规则是每个ASCII字符的二进制值必须是8位。因为较低的ASCII(0到127)只真正代表7位二进制值(即:a=1000001和z=1111010)我们必须确保0填充到二进制值的最左端,以便生成一个确定的8位二进制数。我们需要这样做,因为我们的ACGT翻译要求每个字符有两个二进制数字(即:a=00,C=11,G=10,T=01),因此所有二进制值(附加或不附加)必须可除以2且没有余数。如果我们将所有内容都保留为7位二进制值,则无法完成此操作。现在,知道需要在每个ASCII二进制值的最左边附加一个0以建立8位,我们将发现ACGT字符串将始终以“T”或“a”开头。ACGT字符串将永远不会以“a”开头“C”或“G”。如果这是不可接受的,那么ACGT字符到二进制的转换必须更改,或者ASCII二进制值的填充必须更改。应该是转换发生了更改,因为如果对ASCII二进制值进行了更改,那么这将是对ASCII二进制的错误陈述,这是不好的

另一条规则是ACGT字符到二进制的转换始终保持不变。在整个处理过程中,它从不改变

我在下面提供的新代码执行您在上一篇评论中描述的任务。我将保留我上一篇文章中的前一段代码,因为有人可能会发现它也很有用

在这段新代码中,我使用了一个扫描器来接收来自用户的输入以进行测试。我知道您将从数据库检索字符串,我将让您决定如何在代码中实现它,因为将这段代码的两个转换部分放入方法中是最好的方法

与Java的任何东西一样,有大约12种方法可以做任何事情,但是我在这里特别使用了“for循环”来处理事情,因为我认为这是最容易遵循的方法。一旦代码完全按照您想要的方式工作,您可以以您认为合适的任何方式对其进行优化

以下是代码(复制/粘贴/运行):

导入java.util.array;
导入java.util.Scanner;
公共类字符翻译{
公共静态void main(字符串[]args){
//从用户获取输入。。。
扫描仪输入=新扫描仪(系统输入);
System.out.println(“***将字符串转换为ASCII,将二进制转换为ACGT***\n”);
System.out.println(“请输入一个字符串以转换为ACGT:”);
String inputString=in.nextLine();
//声明并初始化所需的变量。。。
int[]inputAscii=new int[inputString.length()];
String[]inputBinary=新字符串[inputString.length()];
//由二维数组构成的转换表:
字符串[][]ACGTtranslation={{“A”,“00”},{“T”,“01”},{“G”,“10”},{“C”,“11”};
// ------------------------------------------------
public class CharacterTranslation {

    public static void main(String[] args) {
        // Translation Table made from a two dimensional Array:
        String[][] mat1 = {{"A","00"},{"T","01"},{"G","10"},{"C","11"}};
        String input = "GCAT";

        System.out.println("Original Input: " + input);

        // Convert each character within the supplied input string
        // to our binary character translation.
        String translation = "";
        for (int i = 0; i < input.length(); i++) {
            String c = Character.toString(input.charAt(i)); 
            for (int j = 0; j < mat1.length; j++) {
                if (mat1[j][0].equals(c)) { translation+= mat1[j][1]; break; }
            }
        }
        // Display the translation in output console (pane).
        System.out.println("Convert To Binary Translation: " + translation);

        // Now, convert the binary translation back to our 
        // original character input. Note: this only works
        // if the binary translation is only 2 bits for any 
        // character.
        String origInput = "";
        for (int i = 0; i < translation.length(); i+= 2) {
            String b = translation.substring(i, i+2);
            for (int j = 0; j < mat1.length; j++) {
                if (mat1[j][1].equals(b)) { origInput+= mat1[j][0]; break; }
            }
        }

        // Display the converted binary translation back to 
        // it original characters.
        System.out.println("Convert Back To Original Input: " + origInput);
    }

}
import java.util.Arrays;
import java.util.Scanner;

public class CharacterTranslation {

    public static void main(String[] args) {
        // Get Input from User...
        Scanner in = new Scanner (System.in);
        System.out.println("***  CONVERT FROM STRING TO ASCII TO BINARY TO ACGT  ***\n");
        System.out.println("Please enter a String to Convert to ACGT:");
        String inputString = in.nextLine();   

        // Declare and initialize required variables...
        int[] inputAscii = new int[inputString.length()];
        String[] inputBinary = new String[inputString.length()];
        // Translation Table made from a two dimensional Array:
        String[][] ACGTtranslation = {{"A","00"},{"T","01"},{"G","10"},{"C","11"}};

        // ------------------------------------------------
        // --------  CONVERT FROM STRING TO ACGT ----------
        // ------------------------------------------------

        //Convert the input string into ASCII numbers...
        for (int i = 0; i < inputString.length(); i++) {
            char character = inputString.charAt(i); 
            inputAscii[i] = (int) character; 
        }

        System.out.println("Conversion To ASCII:  " + Arrays.toString(inputAscii)
                           .replace("[","").replace("]",""));

        //Convert the ASCII Numbers to 8 bit Binary numbers...
        for (int i = 0; i < inputAscii.length; i++) {
            String bs =  String.valueOf(Integer.toBinaryString(0x100 + 
                         inputAscii[i]).substring(2));
            // Pad the left end of the binary number with 0 should
            // it not be 8 bits. ASCII Charcters will only produce
            // 7 bit binary. We must have 8 bits to acquire a even
            // number of digit pairs for our ACGT convertion.
            while (bs.length() < 8) { bs = "0" + bs; }
            inputBinary[i] = bs; 
        }

        System.out.println("Conversion To 8bit Binary:  " + Arrays.toString(inputBinary)
                           .replace("[","").replace("]",""));

        //Convert the Binary String to ACGT format based from 
        // our translational Two Dimensional String Array.
        // First we append all the binary data together to form
        // a single string of binary numbers then starting from 
        // the left we break off 2 binary digits at a time to 
        // convert to our ACGT string format.

        // Convert the inputBinary Array to a single binary String...
        String binaryString = "";
        for (int i = 0; i < inputBinary.length; i++) {
            binaryString+= String.valueOf(inputBinary[i]);
        }
        // Convert the Binary String to ACGT...
        String ACGTstring = "";
        for (int i = 0; i < binaryString.length(); i+= 2) {
            String tmp = binaryString.substring(i, i+2);
            for (int j = 0; j < ACGTtranslation.length; j++) {
                if (tmp.equals(ACGTtranslation[j][1])) { 
                    ACGTstring+= ACGTtranslation[j][0];
                }            
            }
        }

        System.out.println("The ACGT Translation String for the Word '" +
                           inputString + "' is:  " + ACGTstring + "\n");


        // ------------------------------------------------
        // -----  CONVERT FROM ACGT BACK TO STRING --------
        // ------------------------------------------------

        System.out.println("***  CONVERT FROM ACGT (" + ACGTstring + 
                           "' TO BINARY TO ASCII TO STRING  ***\n");
        System.out.println("Press ENTER Key To Continue...");
        String tmp = in.nextLine();

        // Convert ACGT back to 8bit Binary...

        String translation = "";
        for (int i = 0; i < ACGTstring.length(); i++) {
            String c = Character.toString(ACGTstring.charAt(i)); 
            for (int j = 0; j < ACGTtranslation.length; j++) {
                if (ACGTtranslation[j][0].equals(c)) { translation+= ACGTtranslation[j][1]; break; }
            }
        }

        // We divide the translation String by 8 so as to get 
        // the total number of 8 bit binary numbers that would
        // be contained within that ACGT String. We then reinitialize
        // our inputBinary Array to hold that many binary numbers.
        inputBinary = new String[translation.length() / 8];
        int cntr = 0;
        for (int i = 0; i < translation.length(); i+= 8) {
            inputBinary[cntr] = translation.substring(i, i+8);
            cntr++;
        }
        System.out.println("Conversion from ACGT To 8bit Binary:  " + 
                           Arrays.toString(inputBinary).replace("[","")
                           .replace("]",""));

        //Convert 8bit Binary To ASCII...
        inputAscii = new int[inputBinary.length];
        for (int i = 0; i < inputBinary.length; i++) {
            inputAscii[i] = Integer.parseInt(inputBinary[i], 2);
        }

        System.out.println("Conversion from Binary To ASCII:  " + Arrays.toString(inputAscii)
                           .replace("[","").replace("]",""));

        // Convert ASCII to Character String...
        inputString = "";
        for (int i = 0; i < inputAscii.length; i++) {
            inputString+= Character.toString ((char) inputAscii[i]);
        }

        System.out.println("Conversion from ASCII to Character String:  " + inputString);
        System.out.println("**  Process Complete  ***");
    }
} 
public class MyGUIClassName??? extends javax.swing.JFrame {
    String[][] ACGTtranslation = {{"A","00"},{"T","01"},{"G","10"},{"C","11"}};
    ..............................
    ..............................
    ..............................
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { 
    // Skip this event if there is nothing contained
    // within jTextField1.
    if (jTextField1.getText().isEmpty()) { return; }

    // Get the current text in jButton3.
    String buttonText = jButton3.getText();

    // If the button text reads "Convert To ACGT" then...
    if ("Convert To ACGT".equals(buttonText)) {
        // change the button text to "Convert To String".
        jButton3.setText("Convert To String");
        // Convert the string from database now contained in jTextField1
        // to ACGT format and place that new ACGT into the same JTextfield.
        // We use the StringToACGT() method for this.
        jTextField1.SetText(StringToACGT(jTextField1.getText());
    }

    // The button text must be "Convert To String"...
    else {
        // so let's change the button text to now be "Convert To ACGT"
        // again.
        jButton3.setText("Convert To ACGT");
        // Take the ACGT string now contained within jTextField1
        // from the first button click and convert it back to its 
        // original String format. We use the ACGTtoString() method
        // for this.
        jTextField1.SetText(ACGTtoString(jTextField1.getText());
    } 
}
// CONVERT A STRING TO ACGT FORMAT
public static String StringToACGT(String inputString) {
    // Make sure the input string contains something.
    if ("".equals(inputString)) { return ""; }

    // Declare and initialize required variables...
    int[] inputAscii = new int[inputString.length()];
    String[] inputBinary = new String[inputString.length()];

    //Convert the input string into ASCII numbers...
    for (int i = 0; i < inputString.length(); i++) {
        char character = inputString.charAt(i); 
        inputAscii[i] = (int) character; 
    }

    //Convert the ASCII Numbers to 8 bit Binary numbers...
    for (int i = 0; i < inputAscii.length; i++) {
        String bs =  String.valueOf(Integer.toBinaryString(0x100 + 
                     inputAscii[i]).substring(2));
        // Pad the left end of the binary number with 0 should
        // it not be 8 bits. ASCII Charcters will only produce
        // 7 bit binary. We must have 8 bits to acquire a even
        // number of digit pairs for our ACGT convertion.
        while (bs.length() < 8) { bs = "0" + bs; }
        inputBinary[i] = bs; 
    }

    //Convert the Binary String to ACGT format based from 
    // our translational Two Dimensional String Array.
    // First we append all the binary data together to form
    // a single string of binary numbers then starting from 
    // the left we break off 2 binary digits at a time to 
    // convert to our ACGT string format.

    // Convert the inputBinary Array to a single binary String...
    String binaryString = "";
    for (int i = 0; i < inputBinary.length; i++) {
        binaryString+= String.valueOf(inputBinary[i]);
    }
    // Convert the Binary String to ACGT...
    String ACGTstring = "";
    for (int i = 0; i < binaryString.length(); i+= 2) {
        String tmp = binaryString.substring(i, i+2);
        for (int j = 0; j < ACGTtranslation.length; j++) {
            if (tmp.equals(ACGTtranslation[j][1])) { 
                ACGTstring+= ACGTtranslation[j][0];
            }            
        }
    }
    return ACGTstring;
}


// CONVERT A ACGT STRING BACK TO ITS ORIGINAL STRING STATE.    
public static String ACGTtoString(String inputString) {
    // Make sure the input string contains something.
    if ("".equals(inputString)) { return ""; }
    String ACGTstring = inputString;
    // Declare and initialize required variables...
    int[] inputAscii = new int[inputString.length()];
    String[] inputBinary = new String[inputString.length()];

    // Convert ACGT back to 8bit Binary...
    String translation = "";
    for (int i = 0; i < ACGTstring.length(); i++) {
        String c = Character.toString(ACGTstring.charAt(i)); 
        for (int j = 0; j < ACGTtranslation.length; j++) {
            if (ACGTtranslation[j][0].equals(c)) { translation+= ACGTtranslation[j][1]; break; }
        }
    }

    // We divide the translation String by 8 so as to get 
    // the total number of 8 bit binary numbers that would
    // be contained within that ACGT String. We then reinitialize
    // our inputBinary Array to hold that many binary numbers.
    inputBinary = new String[translation.length() / 8];
    int cntr = 0;
    for (int i = 0; i < translation.length(); i+= 8) {
        inputBinary[cntr] = translation.substring(i, i+8);
        cntr++;
    }

    //Convert 8bit Binary To ASCII...
    inputAscii = new int[inputBinary.length];
    for (int i = 0; i < inputBinary.length; i++) {
        inputAscii[i] = Integer.parseInt(inputBinary[i], 2);
    }

    // Convert ASCII to Character String...
    inputString = "";
    for (int i = 0; i < inputAscii.length; i++) {
        inputString+= Character.toString ((char) inputAscii[i]);
    }

    return inputString;
}