我创建了一个函数,该函数返回存储长值所需的字节数。该值必须在[Long.MIN_VALUE, Long.MAX_VALUE].

private static final int ONE_BYTE_MAX = (1 << 7) - 1; // 127


ONE_BYTE_MAX值为127

private static final int ONE_BYTE_MIN = -(1 << 7);  // -128


ONE_BYTE_MIN值为-128

private static final int TWO_BYTE_MAX = (1 << 15) - 1;

private static final int TWO_BYTE_MIN = -(1 << 15);

private static final int THREE_BYTE_MAX = (1 << 23) - 1;

private static final int THREE_BYTE_MIN = -(1 << 23);

private static final long FOUR_BYTE_MAX = (1L << 31) - 1;

private static final long FOUR_BYTE_MIN = -(1L << 31);

private static final long FIVE_BYTE_MAX = (1L << 39) - 1;

private static final long FIVE_BYTE_MIN = -(1L << 39);

private static final long SIX_BYTE_MAX = (1L << 47) - 1;

private static final long SIX_BYTE_MIN = -(1L << 47);

private static final long SEVEN_BYTE_MAX = (1L << 55) - 1;

private static final long SEVEN_BYTE_MIN = -(1L << 55);


方法

public static int getBytesForLongValue(long value) {
        if (value >= ONE_BYTE_MIN && value <= ONE_BYTE_MAX) {
            return 1;
        } else if (value >= TWO_BYTE_MIN && value <= TWO_BYTE_MAX) {
            return 2;
        } else if (value >= THREE_BYTE_MIN && value <= THREE_BYTE_MAX) {
            return 3;
        } else if (value >= FOUR_BYTE_MIN && value <= FOUR_BYTE_MAX) {
            return 4;
        }else if (value >= FIVE_BYTE_MIN && value <= FIVE_BYTE_MAX) {
            return 5;
        }else if (value >= SIX_BYTE_MIN && value <= SIX_BYTE_MAX) {
            return 6;
        }else if (value >= SEVEN_BYTE_MIN && value <= SEVEN_BYTE_MAX) {
            return 7;
        } else {
            return 8;
        }
    }


在Java中有一种简单的方法吗

最佳答案

尽管我认为对于Java中的长基本类型,我们应该将字节数保留为8,但是还有另一种方法来计算保留长值(包括符号位)的最小字节数。此方法也可以用于计算任何整数的大小,从而调整方法的签名:

public static int getMinNoOfBytes(BigInteger value)


不过,这里是代码:

public class Answer {

    public static int getMinNoOfBytes(long value) {
        BigInteger any = BigInteger.valueOf(value);
        return any.toByteArray().length;
    }


    //Test
    public static void main(String[] args) {

        //Long.MAX_VALYE
        System.out.println(getMinNoOfBytes(Long.MAX_VALUE));

        //Long.MIN_VALUE
        System.out.println(getMinNoOfBytes(Long.MIN_VALUE));

        //Any value
        System.out.println(getMinNoOfBytes(65536));

    }
}


输出是(按预期)

8
8
3

09-25 21:21