如何在Java中将二进制字符串更改为字母数字字符串?

时间:2015-02-24 00:12:04

标签: java

在尝试了关于这个主题的每个答案后,我找到了(并且搜索了将近一整天),我无法将字符串格式(变量a)的二进制数据成功转换为字母数字字符串。我的问题是“我做错了什么?”

最终我想要打印出一个人类可读的字符串,例如“Hello There”,这将是整数87521618088882520788922981(输入将更改为long。)

int input = 256;
    int maxInt = 10000;
    String result = "";
    String o;
    String a = "";
    String stringByte;
    char c;
    int pos;
     while (input <= maxInt){
         System.out.println("Input:          " + input);
         o = Integer.toBinaryString(input);
         System.out.println("Binary String:  " + o);
         System.out.println("Remainder:      " + o.length() % 8);
         if (((o.length() % 8) == 0) && (o != "0")){
             //is a multiple
            a = o;
        }else{
            a = o;
            while ((a.length() % 8 != 0)){
                a = "0" + a;
            }
         }
         //divide into bytes
         System.out.println("Zero-putter:    " + a);
         int numBytes = a.length()/8;
         pos = 1;
         System.out.println("Bytes Received: " + numBytes);
             byte[] bytes = a.getBytes();
             String str = new String(bytes);
         System.out.println("Character:      " + str);
         System.out.println("-----------------------------");
         input++;
         try {
                Thread.sleep(1000);                 //1000 milliseconds is one second.
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }



     }

答案我试过了:
- Binary to text in Java
- Convert binary string to ascii text?
- Parsing a string of binary into text/characters
- How to convert efficiently binary string to binary byte array in Java?
- http://www.dreamincode.net/forums/topic/247956-convert-binary-data-to-text/
- How do I convert a large binary String to byte array java?
- How do I convert a large binary String to byte array java?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用BigInteger将字节数组转换为无限数字。

1-将您的字符串转换为字符数组

char[] chars = myString.getBytes();

2-转换字节数组中的字符数组(字节b =(字节)c,其中c是字符)

byte[] bytes = new byte[chars.length];
for(int i=0; i<bytes.length;i++){
  bytes[i] = (byte)chars[i];
}

3-使用BigInteger

BigInteger myData = new BigInteger(bytes);

4-显示为字符串

myData.toString();