1

So my problem is that i have to recursively find the number of bits, that are required to display / save a number e.g. 4(10)=100(2) so 3 bits would be needed. I think i already know how i am supposed to do it, but my code still doesnt work. Here is what i have so far:

public static int l = 1;
    public static int countUsedBits(long z) {
        if (z == 0) {
            return l;
        } else {
            ++l;
            return countUsedBits(log, z >>> 1);
        }
    }

The problem is that the returned number is always 1 off (too big) of the correct number. Thanks for any help in advance!

vader69
  • 27
  • 3
  • 2
    I don’t understand what you are trying to do (please provide more examples), but if it’s always 1 too big, just subtract 1! – Bohemian Nov 17 '19 at 23:29
  • Note that Java saves `int` values always as `32-bit` value using 2-complement scheme. So the binary you showed is not how it is actually saved in memory. Not sure if that is what you want to compute though. – Zabuzard Nov 17 '19 at 23:38
  • Ok, so i have a decimal number and i want to find the amount of bits required to display this number in binary (i have to do this recursively). I already tried subtracting 1, e.g. "return l-1", but for some reason if i do it actually doesnt change anything. – vader69 Nov 17 '19 at 23:43

1 Answers1

1

The number of bits required to representN in binary is log base 2 of N, referred to a log2 N. Once you get the result, round up, even if the result is integral.

Examples.

  1. log2 of 4 = 2. add 1 and get 3. so 4 requires 3 bits
  2. log2 of 8 = 3. add 1 and get 4. so 8 requires 4 bits.

Note that above, anything between 4 and 7 inclusive, requires 3 bits.

Just remember than a logarithm is basically an exponent. So when you have for a given base of 2 then the result of log2 N is the exponent such that 2^result = N (in this case, ^ means raise to that power).

EDIT:

You're answer was real close. Set l = 0 initially and then return l when z == 0. it should work. And your recursive call should not include anything other than z>>>1.

Note: One problem with your method is that you need to keep resetting l for each call and that is not user friendly. So another way which does not require a separate value is to do the following:

   public static int countUsedBits(long z) {
      if (z == 0) {
         return 0;
      }
      return countUsedBits(z >>> 1) + 1;
   }

I recommend you put in some print statement to see how this progresses.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • ok thank you, but how can i use that information to find the number of bits required with a recursion? – vader69 Nov 17 '19 at 23:49
  • I apologize. I glossed over the recursion part. I will update my answer to assist. – WJS Nov 17 '19 at 23:58