Java Bit Count bitSizeForSignedValue(final int value)

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

Description

bit Size For Signed Value

License

Open Source License

Return

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

Declaration

public static int bitSizeForSignedValue(final int value) 

Method Source Code

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

public class Main {
    /**//  w  w w .ja va 2 s  . c o m
     * @return The number of bits required to store the specified value as a signed integer, i.e. a result in [1,32].
     */
    public static int bitSizeForSignedValue(final int value) {
        if (value > 0) {
            return 33 - Integer.numberOfLeadingZeros(value);
        } else if (value == 0) {
            return 1;
        } else {
            // Works for Integer.MIN_VALUE as well.
            return 33 - Integer.numberOfLeadingZeros(-value - 1);
        }
    }

    /**
     * @return The number of bits required to store the specified value as a signed integer, i.e. a result in [1,64].
     */
    public static int bitSizeForSignedValue(final long value) {
        if (value > 0) {
            return 65 - Long.numberOfLeadingZeros(value);
        } else if (value == 0) {
            return 1;
        } else {
            // Works for Long.MIN_VALUE as well.
            return 65 - Long.numberOfLeadingZeros(-value - 1);
        }
    }
}

Related

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