我创建了一个函数,该函数返回存储长值所需的字节数。该值必须在[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中做
jeck猫
繁星coding
收到一只叮咚
相关分类