- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
* Calculates the minimum number of bits necessary to represent the given number. The
* number should be given in its unsigned form with the starting bits equal to 1 if it is
* signed. Repeatedly compares number to another unsigned int called x.
* x is initialized to 1. The value of x is shifted left i times until x is greater
* than number. Now i is equal to the number of bits the UNSIGNED value of number needs.
* The signed value will need one more bit for the sign so i+1 is returned if the number
* is signed, and i is returned if the number is unsigned.
* @param number the number to compute the size of
* @param bits 1 if number is signed, 0 if unsigned
*/
public static int minBits(int number, int bits)
{
int val = 1;
for (int x = 1; val <= number && !(bits > 32); x <<= 1)
{
val = val | x;
bits++;
}
if (bits > 32)
{
assert false : ("minBits " + bits + " must not exceed 32");
}
return bits;
}
Follow us!