【问题标题】:How do I change a binary string to an alphanumeric string in Java?如何在 Java 中将二进制字符串更改为字母数字字符串?
【发布时间】:2015-02-24 09:53:51
【问题描述】:

在尝试了我能找到的关于这个主题的所有答案之后(并且搜索了将近一整天),我一直无法成功地将字符串格式的二进制数据(变量 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?

【问题讨论】:

  • 列出您尝试过的“关于此主题的所有答案”会很有帮助,这样您就不会收到您声称对您不起作用的重复答案。
  • 字母数字?你的意思是十进制字符串吗?此外,将您的逻辑与扫描器/输入/输出分开会更容易测试。
  • 举个例子说明应该打印什么。
  • @AdrianLeonhard 扫描器已声明但从未使用过。这是我尝试输入“停止循环”命令时迭代的残余。
  • 显示输入和预期输出的清晰示例。目前尚不清楚您的要求和目的是什么。

标签: java


【解决方案1】:

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

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

char[] chars = myString.getBytes();

2- 将字符数组转换为字节数组( byte b = (byte)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();

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 2016-01-14
    • 2017-06-14
    • 2015-06-21
    • 2014-10-24
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多