Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8198934

BigInteger.valueOf(0L).bitLength() is 0 instead of 1

    Details

    • Subcomponent:
    • CPU:
      generic
    • OS:
      generic

      Description

      FULL PRODUCT VERSION :


      ADDITIONAL OS VERSION INFORMATION :
      Darwin Capri.local 17.4.0 Darwin Kernel Version 17.4.0: Sun Dec 17 09:19:54 PST 2017; root:xnu-4570.41.2~1/RELEASE_X86_64 x86_64

      MacOS High Sierra version 10.13.3 (17D102)

      A DESCRIPTION OF THE PROBLEM :
      BigInteger.valueOf(0L).bitLength() and BigInteger.valueOf(0L).bitCount() return 0 however, the number 0 also needs one bit. This is very misleading and can lead to errors when using the string representation of the BigInteger like BigInteger.valueOf(0L).toString(2) which is of course "0" and not "".

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      call BigInteger.valueOf(0L).bitLength() or BigInteger.valueOf(0L).bitCount()

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The number zero is represented by one bit, which is 0. But having no bit makes no sense. I would expect 1 as return value for both methods.

      ACTUAL -
      Both BigInteger.valueOf(0L).bitLength() and BigInteger.valueOf(0L).bitCount() return 0.

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.math.BigInteger;

      public class Test {
          
          public static void main(String[] args) {
              int bitLength = BigInteger.valueOf(0L).bitLength();
              int bitCount = BigInteger.valueOf(0L).bitCount();
              System.out.println("bitLength=" + bitLength + ", expected: 1");
              System.out.println("bitCount=" + bitCount + ", expected: 1");
          }

      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Problem is that it uses the static ZERO object, which itself is initialized as ZERO = new BigInteger(new int[0], 0);. Therefore, the mag.length is zero and the bitLength() will return 0. The solution would be to change the initialization of ZERO with an array with size 1 and the int value 0.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                bpb Brian Burkhalter
                Reporter:
                webbuggrp Webbug Group
              • Votes:
                0 Vote for this issue
                Watchers:
                4 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: