How to convert BigInteger to String in java

前端 未结 9 1601
眼角桃花
眼角桃花 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:42

    When constructing a BigInteger with a string, the string must be formatted as a decimal number. You cannot use letters, unless you specify a radix in the second argument, you can specify up to 36 in the radix. 36 will give you alphanumeric characters only [0-9,a-z], so if you use this, you will have no formatting. You can create: new BigInteger("ihavenospaces", 36) Then to convert back, use a .toString(36)

    BUT TO KEEP FORMATTING: Use the byte[] method that a couple people mentioned. That will pack the data with formatting into the smallest size, and allow you to keep track of number of bytes easily

    That should be perfect for an RSA public key crypto system example program, assuming you keep the number of bytes in the message smaller than the number of bytes of PQ

    (I realize this thread is old)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 13:50
    String input = "0101";
    BigInteger x = new BigInteger ( input , 2 );
    String output = x.toString(2);
    
    0 讨论(0)
  • 2020-12-24 13:56

    //How to solve BigDecimal & BigInteger and return a String.

      BigDecimal x = new BigDecimal( a );
      BigDecimal y = new BigDecimal( b ); 
      BigDecimal result = BigDecimal.ZERO;
      BigDecimal result = x.add(y);
      return String.valueOf(result); 
    
    0 讨论(0)
  • 2020-12-24 13:58

    Use m.toString() or String.valueOf(m). String.valueOf uses toString() but is null safe.

    0 讨论(0)
  • 2020-12-24 13:59

    https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html.

    Every object has a toString() method in Java.

    0 讨论(0)
提交回复
热议问题