BitFieldUtil.java

package zserio.runtime;

/**
 * Provides bit field utilities for code generated by Zserio.
 */
public final class BitFieldUtil
{
    /**
     * Gets the lower bound of a bitfield type with given length.
     *
     * @param length   Length of the bitfield in bits.
     * @param isSigned True if it's a signed bitfield, false otherwise.
     *
     * @return The lowest value the bitfield can hold.
     */
    public static long getBitFieldLowerBound(int length, boolean isSigned)
    {
        if (length <= 0 || length > getMaxBitFieldSize(isSigned))
            throw new ZserioError("getBitFieldLowerBound: Asking for lower bound of bitfield with wrong "
                    + "length " + length + ".");

        if (isSigned)
            return -(1L << (length - 1));
        else
            return 0;
    }

    /**
     * Gets the upper bound of a bitfield type with given length.
     *
     * @param length   Length of the bitfield in bits.
     * @param isSigned True if it's a signed bitfield, false otherwise.
     *
     * @return The largest value the bitfield can hold.
     */
    public static long getBitFieldUpperBound(int length, boolean isSigned)
    {
        if (length <= 0 || length > getMaxBitFieldSize(isSigned))
            throw new ZserioError("getBitFieldUpperBound: Asking for upper bound of bitfield with wrong "
                    + "length " + length + ".");

        if (isSigned)
            return (1L << (length - 1)) - 1;
        else
            return (1L << length) - 1;
    }

    private static int getMaxBitFieldSize(boolean isSigned)
    {
        return isSigned ? MAX_SIGNED_BITFIELD_BITS : MAX_UNSIGNED_BITFIELD_BITS;
    }

    private static final int MAX_SIGNED_BITFIELD_BITS = 64;
    private static final int MAX_UNSIGNED_BITFIELD_BITS = 63;
}