0

For a given unsigned int value, I tried following method for the number of bits for storing given value.

    // Returns the number of required bits for (storing) specified unsigned value.
    static int size(final int value) {
        if (value < 0) {
            throw new IllegalArgumentException("value(" + value + ") is negative");
        }
        return (int) Math.ceil(Math.log10(value) / Math.log10(2));
    }

And here comes what I got.

size for 1310394095: 31              (RANDOM)
size for 1: 0                        (1; Not Good; should be 1)
size_NotNegative_Zero() is @Disabled (0; ERROR; Expecting actual: -2147483648 ...)
size for 2147483647: 31              (Integer.MAX_VALUE)

The 31 for Integer.MAX_VALUE seems OK.

How can I fix this?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

0

Although I flagged my own question as a duplicate, I'm posting what I found.

The problem is that the input is not just positive but also including zero and that's why the way of simply dividing logwhateverv with logwhatever2 won't work cuz logwhatever0 is not defined.

Here comes what I concluded with https://stackoverflow.com/a/680040/330457.

    static int size(final int value) {
        if (value < 0) {
            throw new IllegalArgumentException("value(" + value + ") is negative");
        }
        if (value == 0) {
            return 1;
        }
        return Integer.SIZE - Integer.numberOfLeadingZeros(value);
    }
size for 909663241: 30  (RANDOM)
size for 1: 1           (ONE)
size for 0: 1           (ZERO)
size for 2147483647: 31 (Integer.MAX_VALUE)
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184