BigDecimal Class in Java - Reason for Constant Values

I am developing Java Puzzlers second puzzle.

public class Change {
  public static void main(String args[]) {
    System.out.println(2.00 - 1.10);
  }
}

You will think that the answer is 0.9. But this is not so. If you exercise, you will receive .8999999. The solution is given:

System.out.println(new BigDecimal("2.00").subtract(new BigDecimal("1.10")));

Now it will print 0.9. I understood why it prints 0.89999. But while I'm curious to debug the BigDecimal class, I find that in most places there are many constant values. I have listed everything below and have become interested to find out the reason for this.

BigDecimal.java line number 394,

               while (len > 10 && Character.digit(c, 10) == 0) {
                    offset++;
                    c = in[offset];
                    len--;
                }

Here Character.digit (c, 10).

public static int digit(char ch, int radix) {
        return digit((int)ch, radix);
    }

Here 10 is passed as radix.
Q1. Why is there 10.

BigDecimal.java line number 732

int sign = ((valBits >> 63)==0 ? 1 : -1);
        int exponent = (int) ((valBits >> 52) & 0x7ffL);
        long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
                            : (valBits & ((1L<<52) - 1)) | (1L<<52));
        exponent -= 1075;

Q2. , , valBits, , - ?

Q3. , , 63, 52. ?

Q4. , 0x7ffL . , BitWise & .

, . .

+4
1

Q1: , . 10;)

Q4: 7ff : 0111 1111 1111

, Java " " ? , → 63 63 . - ( ). 1, , int .

, https://en.wikipedia.org/wiki/Floating_point . 52 - .

Q4: , "sign" , , 7ff. 0x7ff ; 0 , . (. "AND" https://en.wikipedia.org/wiki/Truth_table)

Edit:

Q4 : 12, :

0000 0000 1100 ... (positive value) (ex: 1x10^12)
1000 0000 1100 ... (negative value) (ex: -1x10^12)

: 1000 0000 1100 2060 .

"":

  1000 0000 1100 & 0111 1111 1111 -> 0000 0000 1100 (12 decimal)
  AND
  0000 0000 1100 & 0111 1111 1111 -> 0000 0000 1100 (12 decimal)

, 0x7ff .

+2

Source: https://habr.com/ru/post/1599091/


All Articles