1

How is it possible to perform a binary logarithm without using Math? Now I have this Math.log(x) / Math.log(2) and it works but I can't use java.lang.Math.

What can I do?

int bits_necessaris = (int)(log2(nat + 1)); // This is correct

// The function where I'm having trouble

public static int log2(int x) {
    return (something);
}

IMPORTANT: When I performed Math.log(7) / Math.log(2) I got 2.80XXXXX

So I did this:

(int) Math.ceil(Math.log(7) / Math.log(2));

And I get ceil(2.80XXXXX) = 3.

The return of the function has to be rounded up, for example if the solution is 6.777 the return has to be 7.

Manaus
  • 407
  • 5
  • 9

1 Answers1

3

You want to know how many bits are necessary to represent an int? Then there are easier solutions such as:

int bitsNeededFor(int i) {
    int bits = 0;
    while (i > 0) {
        bits++;
        i /= 2;
    }
    return bits;
}

On second thought, the following is faster and easier to understand:

int bitsNeededFor(int i) {
    return 32 - Integer.numberOfLeadingZeros(i);
}
Manaus
  • 407
  • 5
  • 9
meriton
  • 68,356
  • 14
  • 108
  • 175