2

I have a biginteger

BigInteger b = new BigInteger("2389623956378561348065123807561278905618906");

And I need to print all its digits (2, 3, 8, and so on...). How can I do it?

4
  • 3
    Why not just toString() it and loop through the String? Commented May 8, 2014 at 6:40
  • What´s wrong with System.out.println(b)? Commented May 8, 2014 at 6:40
  • 1
    Your title says you want to convert it to an array of "numbers" and in your question you say that you want to print it. What is that you are trying to achieve? Commented May 8, 2014 at 6:42
  • @Evan Knowles Very interesting. Thanks for the hint. It helps. Commented May 8, 2014 at 6:53

2 Answers 2

3

Convert to char array, then decrease from each char the ASCII code of '0' char, to get digits between 0 and 9

char[] digits = b.toString().toCharArray();
for (char digit : digits) {
    digit -= '0';
    System.out.println((int)digit);
}

Note that if you just want to print, don't reduce the '0' ASCII value, and don't cast to int when printing

Sign up to request clarification or add additional context in comments.

Comments

0

Already answered by Evan Knowles and user3322273, but here is another implementation:

byte[] digits = b.getBytes();
for (byte digit : digits) {
    System.out.println (digit & 0xf);
}

What it does is that it masks the (ASCII) value of the digit. For example:

'0' = 48     | In ASCII and Unicode - Decimal
    = 110000 | In binary

Hence, if we obtain the last four bits, then we can get the number. So

48 & 0xf (i.e. 15)
= 11 0000
& 00 1111
=    0000
=    0   | Ultimately in decimal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.