How to convert BigInteger to String in java

前端 未结 9 1659
眼角桃花
眼角桃花 2020-12-24 13:39

I converted a String to BigInteger as follows:

Scanner sc=new Scanner(System.in);
System.out.println(\"enter the message\");
String         


        
9条回答
  •  暖寄归人
    2020-12-24 13:43

    You want to use BigInteger.toByteArray()

    String msg = "Hello there!";
    BigInteger bi = new BigInteger(msg.getBytes());
    System.out.println(new String(bi.toByteArray())); // prints "Hello there!"
    

    The way I understand it is that you're doing the following transformations:

      String  -----------------> byte[] ------------------> BigInteger
              String.getBytes()         BigInteger(byte[])
    

    And you want the reverse:

      BigInteger ------------------------> byte[] ------------------> String
                 BigInteger.toByteArray()          String(byte[])
    

    Note that you probably want to use overloads of String.getBytes() and String(byte[]) that specifies an explicit encoding, otherwise you may run into encoding issues.

提交回复
热议问题