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?
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
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.
toString()it and loop through the String?System.out.println(b)?