将4个字母转换为特定的二进制数字如何将这些二进制转换为ASCII

时间:2015-12-10 13:34:30

标签: java netbeans

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]);
}

我希望这些代码从我们选择的二进制文件转换为ASCII,然后ASCII将知道值

3 个答案:

答案 0 :(得分:0)

Sam,你需要创建一些转换表,以便知道哪个临时二进制位与哪个字符相关,我说makeshift因为00与二进制中的字母“A”没什么相同。这同样适用于您提供的其他字符的二进制表示。二进制表示可能与此无关,因为您可以为特定目的做任何您想做的事情。如果可能的话,正确的表示是在未来的道路上获得更多高级功能的方法而且您不需要转换表,因为您需要做的就是将字符ASCII值转换为二进制,如下所示:

// 65 is the ASCII value for the letter A.
String letterAis = String.valueOf(Integer.toBinaryString(0x100 + 65).substring(2));


ALPHABET IN (8 bit) BINARY, CAPITAL LETTERS

A    01000001       N    01001110
B    01000010       O    01001111
C    01000011       P    01010000
D    01000100       Q    01010001
E    01000101       R    01010010
F    01000110       S    01010011
G    01000111       T    01010100
H    01001000       U    01010101
I    01001001       V    01010110
J    01001010       W    01010111
K    01001011       X    01011000
L    01001100       Y    01011001
M    01001101       Z    01011010



ALPHABET IN (8 bit) BINARY, LOWER CASE

a    01100001       n    01101110
b    01100010       o    01101111
c    01100011       p    01110000
d    01100100       q    01110001
e    01100101       r    01110010
f    01100110       s    01110011
g    01100111       t    01110100
h    01101000       u    01110101
i    01101001       v    01110110
j    01101010       w    01110111
k    01101011       x    01111000
l    01101100       y    01111001
m    01101101       z    01111010

你已经有一个名为mat1 []的数组变量,它包含你的字符串字母,我建议的是使它成为一个二维数组,1列用于保存字母,第二列用于保存该字母的二进制翻译。一旦建立了翻译,您就可以从字母串到二进制和二进制来回转换为字母串。这是代码(只需复制/粘贴并运行):

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);
    }

}

答案 1 :(得分:0)

根据您的上一条评论Sam我相信我现在明白您需要什么,正如您在下面的代码中所看到的那样,如果遵循特定的规则,则相对容易实现。

一个这样的规则是每个ASCII字符的二进制值必须是8位。因为 lower 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字符串总是以&#39; T&#39;或者是&#39; A&#39;。 ACGT字符串永远不会以&#39; C&#39;或者是&#39; G&#39;如果这是不可接受的,那么二进制转换的ACGT字符必须改变,或者填充到我们的ASCII二进制值必须改变。它应该是更改的转换,因为如果对ASCII二进制值进行了更改,那么它将是对ASCII二进制文件的错误表示,这是不好的。

另一个规则是ACGT字符到二进制翻译总是保持不变。它在整个处理过程中永远不会改变。

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

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

与几乎所有Java一样,有大约12种方法可以做任何事情,但我特别使用&#39; for循环&#39;在这里处理事情,因为它是我认为最容易遵循的事情。只要您按照自己想要的方式工作,就可以以任何您认为合适的方式优化此代码。

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

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  ***");
    }
} 

修改

我想补充一点,我在文中提供了一些内容。 ASCII字符集中使用的大多数字符(用于字符串 - ASCII 32到127)由7位二进制值表示,但是上部ASCII字符集(128到255)中的字符用实际的8位二进制表示值。提供的代码将此考虑在内。我编辑了我的答案以适应这一点。

答案 2 :(得分:0)

对于你真正想要做的Sam,我们只需要一个按钮。我们可以使它像两个不同功能之间的切换按钮。一个按钮和一个文本字段。这是非常基本的东西。

转换表2 Dimensional Array应放在GUI类的构造函数下,以便所有方法都可以使用,如下所示:

public class MyGUIClassName??? extends javax.swing.JFrame {
    String[][] ACGTtranslation = {{"A","00"},{"T","01"},{"G","10"},{"C","11"}};
    ..............................
    ..............................
    ..............................
}

然后你的jButton3 ActionPerformed事件看起来像是:

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());
    } 
}

以下是您放入GUI类的方法:

// 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;
}

就像我之前说的Sam,这是非常基本的材料,你应该已经非常好地掌握了Java编程语言,以达到这一点,特别是如果你实际上正在检索要从数据库转换的数据。我的工作是完成。 :o)我希望这有助于你(和其他人)实现你的目标。