Java Bit Count bitSizeForUnsignedValue(final int value)

Here you can find the source of bitSizeForUnsignedValue(final int value)

Description

bit Size For Unsigned Value

License

Open Source License

Parameter

Parameter Description
value An integer value in [0,Integer.MAX_VALUE].

Exception

Parameter Description
IllegalArgumentException if the specified value is < 0.

Return

The number of bits required to store the specified value as an unsigned integer, i.e. a result in [1,31].

Declaration

public static int bitSizeForUnsignedValue(final int value) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*  ww  w . jav  a 2s. c  o m*/
     * @param value
     *            An integer value in [0,Integer.MAX_VALUE].
     * @return The number of bits required to store the specified value as an unsigned integer, i.e. a result in [1,31].
     * @throws IllegalArgumentException
     *             if the specified value is < 0.
     */
    public static int bitSizeForUnsignedValue(final int value) {
        if (value > 0) {
            return 32 - Integer.numberOfLeadingZeros(value);
        } else {
            if (value == 0) {
                return 1;
            } else {
                throw new IllegalArgumentException("unsigned value [" + value + "] must be >= 0");
            }
        }
    }

    /**
     * @param value
     *            An integer value in [0,Long.MAX_VALUE].
     * @return The number of bits required to store the specified value as an unsigned integer, i.e. a result in [1,63].
     * @throws IllegalArgumentException
     *             if the specified value is < 0.
     */
    public static int bitSizeForUnsignedValue(final long value) {
        if (value > 0) {
            return 64 - Long.numberOfLeadingZeros(value);
        } else {
            if (value == 0) {
                return 1;
            } else {
                throw new IllegalArgumentException("unsigned value [" + value + "] must be >= 0");
            }
        }
    }
}

Related

  1. bitLength(byte[] bytes)
  2. bitLength(final int byteLength)
  3. bitLength(int num)
  4. bitLength(int value)
  5. bitSizeForSignedValue(final int value)
  6. countBits (long v)
  7. countBits(byte num)
  8. countBits(final int intValue)
  9. countBits(int i)