简体   繁体   English

如何在Java中编写代码以将纯文本转换为十六进制?

[英]how to write code in java to convert plaintext into hexadecimal?

String key="this is stack Overflow i am implementing aes algorithm"; //plaintext
String binary=stringToBinary(key); //convertion from plain text to binarydigits
String res[]=split_at(binary,8); //split binary digits into 8 bits
int c=0,r=0;

for(int i=0;i<res.length;i++) //convert each 8 bits into hexadecimal
{
    userKey[r][c]=binaryToHex(res[i]);
    c++;
    if(c==4)
    {
        c=0;
        r++;
        if(r==4)
        break;
    }
}
public static String[][] split_at(String str,int no)//method
{
    int i=0;
    int x=0;
    int l=str.length();
    String res[]=new String[(l/no)+1];
    int f=0;
    while(no<1){
        res[f]=str.substring(i,no);
        i=i+x;
        no=no+x;
        f++;
    }
    if(i<1){
        res[f]=str.substring(i,1);
    }
    return res;
}

I have tried this.but i dont know that it is correct or not.tell me is this correct process or not?if not then suggest me how to convert plaintext into hexa decimal. 我试过这个。但是我不知道它是正确的还是不正确。告诉我这是正确的过程吗?

Convert each character of the string to an int : 将字符串的每个字符转换为一个int

int character = (int) str.charAt(i);

Then get a hex representation of the int : 然后获取int的十六进制表示形式:

String hexString = Integer.toHexString(character);

get every character, parse to integer and convert it to hexadecimal 获取每个字符,解析为整数并将其转换为十六进制

Example: 例:

public static void main(String args[]) throws InterruptedException {
String key = "Hello world";// plaintext
byte[] x = key.getBytes();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < x.length; i++) {
    int b = (int) x[i];
    sb.append(Integer.toHexString(b));
}
System.out.println(sb.toString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM