Integer
package java.lang;
import java.lang.annotation.Native;
/**
* Integer 类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。
*/
public final class Integer extends Number implements Comparable<Integer> {
/**
* 值为 -2^31 的常量,它表示 int 类型能够表示的最小值。
*
* @Native表明一个字段引用的值可能来自于本地代码
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
* 值为 2^31-1 的常量,它表示 int 类型能够表示的最大值。
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
/**
* 表示基本类型 int 的 Class 实例
*/
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
/**
* 将数字和字母放到数组里作为基数使用
*/
final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
/**
* 返回当第一个参数以第二个参数为基数时,应该表示为什么样的字符串
*/
public static String toString(int i, int radix) {
//如果radix小于2或者大于32,默认采用十进制进行转换
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
/* Use the faster version */
if (radix == 10) {
return toString(i);
}
char buf[] = new char[33];
boolean negative = (i < 0);
int charPos = 32;
//将正数转为负数
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = digits[-(i % radix)];
i = i / radix;
}
buf[charPos] = digits[-i];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (33 - charPos));
}
/**
* 以第二个参数指定的数字为基数,将第一个参数转为一个无符号字符串。
*/
public static String toUnsignedString(int i, int radix) {
return Long.toUnsignedString(toUnsignedLong(i), radix);
}
/**
* 将一个int转为16进制
*/
public static String toHexString(int i) {
return toUnsignedString0(i, 4);
}
/**
* 将int转为8进制
*/
public static String toOctalString(int i) {
return toUnsignedString0(i, 3);
}
/**
* 将int转为二进制
*/
public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}
/**
* 将一个数字转为16或8或2进制字符串
*/
private static String toUnsignedString0(int val, int shift) {
// assert shift > 0 && shift <=5 : "Illegal shift value";
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
//确定表示数字需要多少个字符
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];
formatUnsignedInt(val, shift, buf, 0, chars);
// Use special constructor which takes over "buf".
return new String(buf, true);
}
/**
* 将一个int数字转为char数组
* 其中进制shift的取值为4(16进制),3(8进制),1(2进制)
*/
static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;
int mask = radix - 1;
//val & mask 相当于val % radix 但是这种用法只对进制是2的倍数的进制有效
do {
buf[offset + --charPos] = Integer.digits[val & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}
final static char [] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
} ;
final static char [] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
/**
* int转为十进制的String
*/
public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "-2147483648";
//确定表示数字i需要多少个字符
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}
/**
* 将int值转为无符号十进制的字符串
*/
public static String toUnsignedString(int i) {
return Long.toString(toUnsignedLong(i));
}
/**
* 将int数字转为char数组
*
* 因为有i=-i,所以如果i为int的最小值会报错
*/
static void getChars(int i, int index, char[] buf) {
int q, r;
int charPos = index;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Generate two digits per iteration
while (i >= 65536) {
q = i / 100;
//其实r=i - (q*64)-(q*32)-(q*4)=i-q*100
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
//取出十位数中的个位
buf [--charPos] = DigitOnes[r];
//取出十位数中的十位
buf [--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
for (;;) {
//等效q=i/10
q = (i * 52429) >>> (16+3);
// r = i-(q*10)
r = i - ((q << 3) + (q << 1));
buf [--charPos] = digits [r];
i = q;
if (i == 0) break;
}
//如果是负数,将'-'放进去
if (sign != 0) {
buf [--charPos] = sign;
}
}
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
/**
* 返回数字x的位数
* @param x
* @return
*/
static int stringSize(int x) {
//这种循环没有可判断条件,因此如果数组没有查询到满足条件的,会在最后一次报超出范围的异常
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
/**
* 将字符串以给定的进制转为int
*/
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
//将字符以给定的进制转为int
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
//之前得到的数字乘以进制
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
//加上这次得到的数
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
/**
* 将字符串以十进制转为int
*/
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
/**
* 将字符串解析为以第二个参数为基数的无符号整数,且字符串不能出现负号
*/
public static int parseUnsignedInt(String s, int radix)
throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar == '-') {
throw new
NumberFormatException(String.format("Illegal leading minus sign " +
"on unsigned string %s.", s));
} else {
if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
(radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
return parseInt(s, radix);
} else {
long ell = Long.parseLong(s, radix);
if ((ell & 0xffff_ffff_0000_0000L) == 0) {
return (int) ell;
} else {
throw new
NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned int.", s));
}
}
}
} else {
throw NumberFormatException.forInputString(s);
}
}
/**
* 将字符串参数解析为无符号十进制int。 字符串所表示的数字必须是十进制数字,且不能出现负号
*/
public static int parseUnsignedInt(String s) throws NumberFormatException {
return parseUnsignedInt(s, 10);
}
/**
* 将字符串s以radix指定的进制进行解析,并返回对应的integer
*/
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
/**
* 将字符串s以10进制进行解析,并返回对应的integer
*/
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
/**
* integer
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
/**
* 返回对应int值i的integer,注:在-128到127之间的值(包括这两)是从一个缓存类里取的,另外的是现生成的,这么做是为了增加性能
* 所以使用这个方法时同样的int值,取两次如果值在-128到127之间你取到的是同一个integer,其他的值是不同的两个integer
*
* 注:Integer i = 12;这种取值方法默认调用此方法
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
/**
* integer的值
*/
private final int value;
/**
*
*/
public Integer(int value) {
this.value = value;
}
/**
*
*/
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
/**
*
*/
public byte byteValue() {
return (byte)value;
}
/**
*
*/
public short shortValue() {
return (short)value;
}
/**
*
*/
public int intValue() {
return value;
}
/**
* 返回integer的long值,由于这种转换的方式,所以如果integer是负数,转换为long值后与原值相同,注意和toUnsignedLong方法的不同
*/
public long longValue() {
return (long)value;
}
/**
*
*/
public float floatValue() {
return (float)value;
}
/**
*
*/
public double doubleValue() {
return (double)value;
}
/**
*
*/
public String toString() {
return toString(value);
}
/**
*
*/
@Override
public int hashCode() {
return Integer.hashCode(value);
}
/**
*
*/
public static int hashCode(int value) {
return value;
}
/**
*
*/
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
/**
* 通过 System.getProperty(java.lang.String) 方法可以访问系统属性。
* 然后,将该属性的字符串值解释为一个整数值,并返回表示该值的 Integer 对象。
* 使用 getProperty 的定义可以找到可能出现的数字格式的详细信息。
*/
public static Integer getInteger(String nm) {
return getInteger(nm, null);
}
/**
* 第一个参数被视为系统属性的名称。通过 System.getProperty(java.lang.String) 方法可以访问系统属性。
* 然后,将该属性的字符串值解释为一个整数值,并返回表示该值的 Integer 对象。
* 使用 getProperty 的定义可以找到可能出现的数字格式的详细信息。
*
*
* 第二个参数是默认值。如果未具有指定名称的属性,或者属性的数字格式不正确,或者指定名称为空或 null,
* 则返回一个表示第二个参数的值的 Integer 对象。
*/
public static Integer getInteger(String nm, int val) {
Integer result = getInteger(nm, null);
return (result == null) ? Integer.valueOf(val) : result;
}
/**
* 返回具有指定名称的系统属性的整数值。
* 第一个参数被视为系统属性的名称。通过 System.getProperty(java.lang.String) 方法可以访问系统属性。
* 然后,根据Integer.decode 方法,将该属性的字符串值解释为一个整数值,并返回一个表示该值的 Integer 对象。
*
*
* 第二个参数是默认值。如果未具有指定名称的属性,或者属性的数字格式不正确,或者指定名称为空或 null,则返回默认值。
*
*/
public static Integer getInteger(String nm, Integer val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Integer.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
}
/**
* 将 String 解码为 Integer,
* 其中以负号打头的会被解析为负数,+解析为正数
* 0x和#打头的解析为16进制
* 0打头解析为8进制
*/
public static Integer decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Integer result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Integer.valueOf(nm.substring(index), radix);
result = negative ? Integer.valueOf(-result.intValue()) : result;
} catch (NumberFormatException e) {
// If number is Integer.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Integer.valueOf(constant, radix);
}
return result;
}
/**
* 比较两个Integer值的大小,如果
* 本>anotherInteger 返回1
* 本==anotherInteger 返回0
* 本<anotherInteger 返回-1
*/
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
/**
* 比较两个int的大小,如果x大返回1,x小返回-1,相等返回0
*/
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
/**
* 比较x和y,在这个方法里,负数永远比非负数大,负数中-1最大
*/
public static int compareUnsigned(int x, int y) {
//加上integer的最小值,
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
/**
* 将int转为一个无符号的long值,其中当x等于0或者大于0时,long值与其相等,
* 如果为负数转为int后按照按位与的计算会加上2^32
*/
public static long toUnsignedLong(int x) {
return ((long) x) & 0xffffffffL;
}
/**
* 使用toUnsignedLong方法将两个int转为无符号long,相除之后再强转为int
*/
public static int divideUnsigned(int dividend, int divisor) {
// In lieu of tricky code, for now just use long arithmetic.
return (int)(toUnsignedLong(dividend) / toUnsignedLong(divisor));
}
/**
* 使用toUnsignedLong方法将两个int转为无符号long然后dividend%divisor,得到的值强转为int
*/
public static int remainderUnsigned(int dividend, int divisor) {
// In lieu of tricky code, for now just use long arithmetic.
return (int)(toUnsignedLong(dividend) % toUnsignedLong(divisor));
}
// Bit twiddling
/**
* int的位数
*/
@Native public static final int SIZE = 32;
/**
* int的字节数
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
* 取到int值二进制中最高位,且将其他位取为0后,返回该二进制的int值
* 例如111的二进制1101111,返回1000000
* i |= j 相当于 i = i | j
*/
public static int highestOneBit(int i) {
// 以1101111例子解释
//这一步的意思是i等于1101111,和1101111右移一位即0110111的按位或,得到1111111
//这步相当于将第一位和第二位全变为1
i |= (i >> 1);
//上一步将前两位变为1,这步将前四位变为1,下面依次类推
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
//这一步将除第一位的1保留,其他的都被剪掉了
return i - (i >>> 1);
}
/**
* 取得int值二进制中最低位的1,且将其他位取为0后,返回改二进制的int值
* 例如110的二进制1101110为返回0000010,
* 其中-110的二进制为11111111111111111111111110010010
* 根据补码规则,负数的二进制为正数二进制取反之后加1
*/
public static int lowestOneBit(int i) {
// HD, Section 2-1
return i & -i;
}
/**
* 返回在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前的零位的数量
* 例如00000000 00000000 011111111 111111111返回16
* 符号位不包含
* 如果值为零,则返回 32
*/
public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
return 32;
int n = 1;
//i <<= 16 相当于 i = i << 16
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
//如果为负数,减1
n -= i >>> 31;
return n;
}
/**
* 返回指定的 int 值的二进制补码表示形式中最低(“最右边”)的为 1 的位后面的零位个数。
* 如果值为零,则返回 32
* 同样的该方法也只返回几个特定的值
*/
public static int numberOfTrailingZeros(int i) {
// HD, Figure 5-14
int y;
if (i == 0) return 32;
int n = 31;
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}
/**
* 返回指定 int 值的二进制补码表示形式的 1 位的数量。此函数有时用于人口普查。
*/
public static int bitCount(int i) {
// HD, Figure 5-2
//0x55555555的二进制01010101010101010101010101010101
i = i - ((i >>> 1) & 0x55555555);
//0x33333333的二进制00110011001100110011001100110011
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
//0x0f0f0f0f的二进制00001111000011110000111100001111
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
//0x3f的二进制111111
return i & 0x3f;
}
/**
* 返回根据指定的位数循环左移指定的 int 值的二进制补码表示形式而得到的值。
* (位是从左边(即高位)移出,从右边(即低位)再进入),(符号位也在移的位中)
* 例如Integer.toBinaryString(1280000001)
* 1280000001的二进制为:01001100 01001011 01000000 00000001
* 结果为:01001011 01000000 00000001 01001100
*
*
* 1280000001 >>> -8的效果如下
* 1280000001的二进制:01001100010010110100000000000001
* 1280000001 >>> -8:01001100
*/
public static int rotateLeft(int i, int distance) {
return (i << distance) | (i >>> -distance);
}
/**
* 返回根据指定的位数循环右移指定的 int 值的二进制补码表示形式而得到的值。
* (位是从右边(即低位)移出,从左边(即高位)再进入)
* 例如Integer.rotateRight(-1280000001, 8)
* -1280000001的二进制:10110011101101001011111111111111
* 结果:11111111101100111011010010111111
*
*
* -1280000001 << -8的结果如下
* -1280000001的二进制:10110011101101001011111111111111
* -1280000001 << -8的结果:11111111000000000000000000000000
*/
public static int rotateRight(int i, int distance) {
return (i >>> distance) | (i << -distance);
}
/**
* 返回通过反转指定 int 值的二进制补码表示形式中位的顺序而获得的值。
* 例如:Integer.reverse(-1280000001)
* -1280000001的二进制:10110011101101001011111111111111
* 结果的二进制为: 11111111111111010010110111001101
* 即为第一个完全颠倒过来
*/
public static int reverse(int i) {
// HD, Figure 7-1
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
i = (i << 24) | ((i & 0xff00) << 8) |
((i >>> 8) & 0xff00) | (i >>> 24);
return i;
}
/**
* 返回指定 int 值的符号函数。(如果指定值为负,则返回 -1;如果指定值为零,则返回 0;如果指定的值为正,则返回 1。)
*
*
* >>:带符号右移。正数右移高位补0,负数右移高位补1
* >>>:无符号右移。无论是正数还是负数,高位通通补0
*/
public static int signum(int i) {
// HD, Section 2-7
return (i >> 31) | (-i >>> 31);
}
/**
* 返回通过反转指定 int 值的二进制补码表示形式中字节的顺序而获得的值。
* 因为一个字节占8位,所以
* 以Integer.reverseBytes(-1280000001)作为例子
* -1280000001的二进制:10110011 10110100 10111111 11111111
* 结果的二进制为 11111111 10111111 10110100 10110011
* 即为每8个一组完全颠倒
*/
public static int reverseBytes(int i) {
return ((i >>> 24) ) |
((i >> 8) & 0xFF00) |
((i << 8) & 0xFF0000) |
((i << 24));
}
/**
* 计算两个值的和
*/
public static int sum(int a, int b) {
return a + b;
}
/**
* 计算两个值的最大值
*/
public static int max(int a, int b) {
return Math.max(a, b);
}
/**
* 计算两个值的最小值
*/
public static int min(int a, int b) {
return Math.min(a, b);
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
@Native private static final long serialVersionUID = 1360826667806852920L;
}
Byte
package java.lang;
/**
*
* Byte 类将基本类型 byte 的值包装在一个对象中。一个 Byte 类型的对象只包含一个类型为 byte 的字段。
*/
public final class Byte extends Number implements Comparable<Byte> {
/**
* 最小值
*/
public static final byte MIN_VALUE = -128;
/**
* 最大值
*/
public static final byte MAX_VALUE = 127;
/**
* 表示基本类型 byte 的 Class 实例
*/
@SuppressWarnings("unchecked")
public static final Class<Byte> TYPE = (Class<Byte>) Class.getPrimitiveClass("byte");
/**
* 重写toString方法
*/
public static String toString(byte b) {
return Integer.toString((int)b, 10);
}
/**
* 将-128到127共256个整数值的Byte对象放到cache数组里
*@description
*@auther panmingshuai
*@time 2018年4月17日下午11:45:42
*
*/
private static class ByteCache {
private ByteCache(){}
static final Byte cache[] = new Byte[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Byte((byte)(i - 128));
}
}
/**
* 由byte的值返回Byte对象
*/
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
/**
* 将 string 参数解析为一个有符号的 byte,字符串的基数由第二个参数指定。
*
*/
public static byte parseByte(String s, int radix)
throws NumberFormatException {
int i = Integer.parseInt(s, radix);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value out of range. Value:\"" + s + "\" Radix:" + radix);
return (byte)i;
}
/**
* 将 string参数以十进制解析为有符号的 byte
*/
public static byte parseByte(String s) throws NumberFormatException {
return parseByte(s, 10);
}
/**
* 将 string 参数解析为一个有符号的 Byte对象,字符串的基数由第二个参数指定。
*/
public static Byte valueOf(String s, int radix)
throws NumberFormatException {
return valueOf(parseByte(s, radix));
}
/**
* 将 string参数以十进制解析为有符号的 Byte对象
*/
public static Byte valueOf(String s) throws NumberFormatException {
return valueOf(s, 10);
}
/**
* 调用Integer的decode方法对字符串进行转码,如果字符串代表的值在Byte的范围内,将其转为Byte
*/
public static Byte decode(String nm) throws NumberFormatException {
int i = Integer.decode(nm);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value " + i + " out of range from input " + nm);
return valueOf((byte)i);
}
/**
* Byte的值
*/
private final byte value;
/**
*
*/
public Byte(byte value) {
this.value = value;
}
/**
* 字符串构造方法,字符串的值会被用10为基数进行解析
*/
public Byte(String s) throws NumberFormatException {
this.value = parseByte(s, 10);
}
/**
* 返回值
*/
public byte byteValue() {
return value;
}
/**
* 转为short
*/
public short shortValue() {
return (short)value;
}
/**
* 转为int
*/
public int intValue() {
return (int)value;
}
/**
* 转为long
*/
public long longValue() {
return (long)value;
}
/**
* 转为float
*/
public float floatValue() {
return (float)value;
}
/**
* 转为double
*/
public double doubleValue() {
return (double)value;
}
/**
* 调用Integer.toString实现toString方法
*/
public String toString() {
return Integer.toString((int)value);
}
/**
*
*/
@Override
public int hashCode() {
return Byte.hashCode(value);
}
/**
*
*/
public static int hashCode(byte value) {
return (int)value;
}
/**
*
*/
public boolean equals(Object obj) {
if (obj instanceof Byte) {
return value == ((Byte)obj).byteValue();
}
return false;
}
/**
* 本>anotherByte 返回1
* 本==anotherByte 返回0
* 本<anotherByte 返回-1
*/
public int compareTo(Byte anotherByte) {
return compare(this.value, anotherByte.value);
}
/**
* x>y 返回1
* x==y 返回0
* x<y 返回-1
*/
public static int compare(byte x, byte y) {
return x - y;
}
/**
* 转换为无符号 int的值,因为这个方法是用按位与进行计算的,所以负数使用这个方法会增加2^8
*/
public static int toUnsignedInt(byte x) {
return ((int) x) & 0xff;
}
/**
* 转换为无符号 long的值,因为这个方法是用按位与进行计算的,所以负数使用这个方法会增加2^8
*/
public static long toUnsignedLong(byte x) {
return ((long) x) & 0xffL;
}
/**
*
*/
public static final int SIZE = 8;
/**
* The number of bytes used to represent a {@code byte} value in two's
* complement binary form.
*
* @since 1.8
*/
public static final int BYTES = SIZE / Byte.SIZE;
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = -7183698231559129828L;
}
Short
package java.lang;
/**
* Short 类在对象中包装基本类型 short 的值。一个 Short 类型的对象只包含一个 short 类型的字段。
*/
public final class Short extends Number implements Comparable<Short> {
/**
* 最小值-2^15
*/
public static final short MIN_VALUE = -32768;
/**
* 最大值2^15-1.
*/
public static final short MAX_VALUE = 32767;
/**
* 表示基本类型 short 的 Class 实例
*/
@SuppressWarnings("unchecked")
public static final Class<Short> TYPE = (Class<Short>) Class.getPrimitiveClass("short");
/**
* 调用Integer.toString实现
*/
public static String toString(short s) {
return Integer.toString((int)s, 10);
}
/**
* 将字符串s解析为由第二个参数radix指定的基数的有符号的 short。
*/
public static short parseShort(String s, int radix)
throws NumberFormatException {
int i = Integer.parseInt(s, radix);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value out of range. Value:\"" + s + "\" Radix:" + radix);
return (short)i;
}
/**
* 将字符串s解析为基数为10的有符号的 short。
*/
public static short parseShort(String s) throws NumberFormatException {
return parseShort(s, 10);
}
/**
* 返回一个 Short 对象,该对象保存从字符串s中以radix为基数转换的short值
*/
public static Short valueOf(String s, int radix)
throws NumberFormatException {
return valueOf(parseShort(s, radix));
}
/**
* 返回一个 Short 对象,该对象保存从字符串s中以10为基数转换的short值
*/
public static Short valueOf(String s) throws NumberFormatException {
return valueOf(s, 10);
}
/**
* short的缓存类,缓存-128到127之间的数
*@description
*@auther panmingshuai
*@time 2018年4月24日下午11:58:30
*
*/
private static class ShortCache {
private ShortCache(){}
static final Short cache[] = new Short[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}
/**
*
*/
public static Short valueOf(short s) {
final int offset = 128;
int sAsInt = s;
if (sAsInt >= -128 && sAsInt <= 127) { // must cache
return ShortCache.cache[sAsInt + offset];
}
return new Short(s);
}
/**
* 将 String 解码为 Short
* 调用Integer.decode实现
*/
public static Short decode(String nm) throws NumberFormatException {
int i = Integer.decode(nm);
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value " + i + " out of range from input " + nm);
return valueOf((short)i);
}
/**
*
*/
private final short value;
/**
*
*/
public Short(short value) {
this.value = value;
}
/**
*
*/
public Short(String s) throws NumberFormatException {
this.value = parseShort(s, 10);
}
/**
*
*/
public byte byteValue() {
return (byte)value;
}
/**
*
*/
public short shortValue() {
return value;
}
/**
*
*/
public int intValue() {
return (int)value;
}
/**
*
*/
public long longValue() {
return (long)value;
}
/**
*
*/
public float floatValue() {
return (float)value;
}
/**
*
*/
public double doubleValue() {
return (double)value;
}
/**
* 调用Integer.toString实现
*/
public String toString() {
return Integer.toString((int)value);
}
/**
*
*/
@Override
public int hashCode() {
return Short.hashCode(value);
}
/**
*
*/
public static int hashCode(short value) {
return (int)value;
}
/**
*
*/
public boolean equals(Object obj) {
if (obj instanceof Short) {
return value == ((Short)obj).shortValue();
}
return false;
}
/**
* 本>anotherByte 返回1
* 本==anotherByte 返回0
* 本<anotherByte 返回-1
*/
public int compareTo(Short anotherShort) {
return compare(this.value, anotherShort.value);
}
/**
* x>y 返回1
* x==y 返回0
* x<y 返回-1
*/
public static int compare(short x, short y) {
return x - y;
}
/**
*
*/
public static final int SIZE = 16;
/**
*
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
* 类似integer.reverseBytes方法
*/
public static short reverseBytes(short i) {
return (short) (((i & 0xFF00) >> 8) | (i << 8));
}
/**
* 转换为无符号 int的值,因为这个方法是用按位与进行计算的,所以负数使用这个方法会增加2^16
*/
public static int toUnsignedInt(short x) {
return ((int) x) & 0xffff;
}
/**
* 转换为无符号 long的值,因为这个方法是用按位与进行计算的,所以负数使用这个方法会增加2^16
*/
public static long toUnsignedLong(short x) {
return ((long) x) & 0xffffL;
}
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = 7515723908773894738L;
}
Long
package java.lang;
import java.lang.annotation.Native;
import java.math.*;
/**
* Long 类在对象中包装了基本类型 long 的值。每个 Long 类型的对象都包含一个 long 类型的字段。
*/
public final class Long extends Number implements Comparable<Long> {
/**
* 最小值:-2^63
* -9223372036854775808
*/
@Native public static final long MIN_VALUE = 0x8000000000000000L;
/**
* 最大值: 2^63-1.
* 9223372036854775807
*/
@Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
/**
* 表示基本类型 int 的 Class 实例
*/
@SuppressWarnings("unchecked")
public static final Class<Long> TYPE = (Class<Long>) Class.getPrimitiveClass("long");
/**
* 返回当第一个参数以第二个参数为基数时,应该表示为什么样的字符串
* 类似:integer.toString(int i, int radix)方法
*/
public static String toString(long i, int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
if (radix == 10)
return toString(i);
char[] buf = new char[65];
int charPos = 64;
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = Integer.digits[(int)(-(i % radix))];
i = i / radix;
}
buf[charPos] = Integer.digits[(int)(-i)];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (65 - charPos));
}
/**
* 将long值转为以radix为基数的无符号字符串
*
* 如果基数小于Character.MIN_RADIX或大于Character.MAX_RADIX ,则使用基数10
*/
public static String toUnsignedString(long i, int radix) {
if (i >= 0)
return toString(i, radix);
else {
switch (radix) {
case 2:
return toBinaryString(i);
case 4:
return toUnsignedString0(i, 2);
case 8:
return toOctalString(i);
case 10:
/*
* We can get the effect of an unsigned division by 10
* on a long value by first shifting right, yielding a
* positive value, and then dividing by 5. This
* allows the last digit and preceding digits to be
* isolated more quickly than by an initial conversion
* to BigInteger.
*/
/*
* quot = (i >>> 1) / 5;相当于i/10
*/
long quot = (i >>> 1) / 5;
long rem = i - quot * 10;
return toString(quot) + rem;
case 16:
return toHexString(i);
case 32:
return toUnsignedString0(i, 5);
default:
return toUnsignedBigInteger(i).toString(radix);
}
}
}
/**
* 将long值转为BigInteger
*/
private static BigInteger toUnsignedBigInteger(long i) {
if (i >= 0L)
return BigInteger.valueOf(i);
else {
int upper = (int) (i >>> 32);
int lower = (int) i;
// return (upper << 32) + lower
return (BigInteger.valueOf(Integer.toUnsignedLong(upper))).shiftLeft(32).
add(BigInteger.valueOf(Integer.toUnsignedLong(lower)));
}
}
/**
* 将long转为无符号16进制
*/
public static String toHexString(long i) {
return toUnsignedString0(i, 4);
}
/**
* 将long转为无符号8进制
*/
public static String toOctalString(long i) {
return toUnsignedString0(i, 3);
}
/**
* 将long转为无符号二进制
*/
public static String toBinaryString(long i) {
return toUnsignedString0(i, 1);
}
/**
* 将一个数字转为16或8或4或2进制字符串
*/
static String toUnsignedString0(long val, int shift) {
// 判断数字的实际有效位数是多少位
int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
//根据进制判断需要多少个字符才能表示val
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];
formatUnsignedLong(val, shift, buf, 0, chars);
return new String(buf, true);
}
/**
* 将一个long数字转为char数组
* 其中进制shift的取值为4(16进制),3(8进制),2(4进制),1(2进制)
*/
static int formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;
int mask = radix - 1;
//val & mask 相当于val % radix 但是这种用法只对进制是2的倍数的进制有效
do {
buf[offset + --charPos] = Integer.digits[((int) val) & mask];
val >>>= shift;
} while (val != 0 && charPos > 0);
return charPos;
}
/**
* 将long值转为十进制的字符串
*/
public static String toString(long i) {
if (i == Long.MIN_VALUE)
return "-9223372036854775808";
//确定表示数字i需要多少个字符
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}
/**
* 将long值转为无符号的十进制字符串
*/
public static String toUnsignedString(long i) {
return toUnsignedString(i, 10);
}
/**
* 将long数字转为char数组
*
* 因为有i=-i,所以如果i为long的最小值会报错
* 类似integer.getChars(int i, int index, char[] buf)方法
*/
static void getChars(long i, int index, char[] buf) {
long q;
int r;
int charPos = index;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Get 2 digits/iteration using longs until quotient fits into an int
while (i > Integer.MAX_VALUE) {
q = i / 100;
// really: r = i - (q * 100);
r = (int)(i - ((q << 6) + (q << 5) + (q << 2)));
i = q;
buf[--charPos] = Integer.DigitOnes[r];
buf[--charPos] = Integer.DigitTens[r];
}
// Get 2 digits/iteration using ints
int q2;
int i2 = (int)i;
while (i2 >= 65536) {
q2 = i2 / 100;
// really: r = i2 - (q * 100);
r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));
i2 = q2;
buf[--charPos] = Integer.DigitOnes[r];
buf[--charPos] = Integer.DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i2 <= 65536, i2);
for (;;) {
q2 = (i2 * 52429) >>> (16+3);
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
buf[--charPos] = Integer.digits[r];
i2 = q2;
if (i2 == 0) break;
}
if (sign != 0) {
buf[--charPos] = sign;
}
}
/**
* 获取long值以十进制表示时有多少位
* @param x
* @return
*/
static int stringSize(long x) {
long p = 10;
for (int i=1; i<19; i++) {
if (x < p)
return i;
p = 10*p;
}
return 19;
}
/**
* 将字符串以给定的进制转为long
*
* parseLong("0", 10) returns 0L
* parseLong("473", 10) returns 473L
* parseLong("+42", 10) returns 42L
* parseLong("-0", 10) returns 0L
* parseLong("-FF", 16) returns -255L
* parseLong("1100110", 2) returns 102L
* parseLong("99", 8) throws a NumberFormatException
* parseLong("Hazelnut", 10) throws a NumberFormatException
* parseLong("Hazelnut", 36) returns 1356099454469L
*/
public static long parseLong(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
long result = 0;
boolean negative = false;
int i = 0, len = s.length();
long limit = -Long.MAX_VALUE;
long multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
/**
* 将字符串以十进制转为long
*/
public static long parseLong(String s) throws NumberFormatException {
return parseLong(s, 10);
}
/**
* 将字符串解析为以第二个参数为基数的无符号整数,且字符串不能出现负号
*/
public static long parseUnsignedLong(String s, int radix)
throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar == '-') {
throw new
NumberFormatException(String.format("Illegal leading minus sign " +
"on unsigned string %s.", s));
} else {
if (len <= 12 || // Long.MAX_VALUE in Character.MAX_RADIX is 13 digits
(radix == 10 && len <= 18) ) { // Long.MAX_VALUE in base 10 is 19 digits
return parseLong(s, radix);
}
// No need for range checks on len due to testing above.
long first = parseLong(s.substring(0, len - 1), radix);
int second = Character.digit(s.charAt(len - 1), radix);
if (second < 0) {
throw new NumberFormatException("Bad digit at end of " + s);
}
long result = first * radix + second;
if (compareUnsigned(result, first) < 0) {
/*
* The maximum unsigned value, (2^64)-1, takes at
* most one more digit to represent than the
* maximum signed value, (2^63)-1. Therefore,
* parsing (len - 1) digits will be appropriately
* in-range of the signed parsing. In other
* words, if parsing (len -1) digits overflows
* signed parsing, parsing len digits will
* certainly overflow unsigned parsing.
*
* The compareUnsigned check above catches
* situations where an unsigned overflow occurs
* incorporating the contribution of the final
* digit.
*/
throw new NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned long.", s));
}
return result;
}
} else {
throw NumberFormatException.forInputString(s);
}
}
/**
* 将字符串参数解析为无符号十进制long。 字符串所表示的数字必须是十进制数字,且不能出现负号
*/
public static long parseUnsignedLong(String s) throws NumberFormatException {
return parseUnsignedLong(s, 10);
}
/**
* 将字符串s以radix指定的进制进行解析,并返回对应的Long
*/
public static Long valueOf(String s, int radix) throws NumberFormatException {
return Long.valueOf(parseLong(s, radix));
}
/**
* 将字符串s以10进制进行解析,并返回对应的Long
*/
public static Long valueOf(String s) throws NumberFormatException
{
return Long.valueOf(parseLong(s, 10));
}
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
/**
* 返回对应long值l的Long,注:在-128到127之间的值(包括这两)是从一个缓存类里取的,另外的是现生成的,这么做是为了增加性能
* 所以使用这个方法时同样的long值,取两次如果值在-128到127之间你取到的是同一个Long,其他的值是不同的两个Long
*
* 注:Long i = 12l;这种取值方法默认调用此方法
*/
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
/**
* 将 String 解码为 Long,
* 其中以负号打头的会被解析为负数,+解析为正数
* 0x和#打头的解析为16进制
* 0打头解析为8进制
*/
public static Long decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Long result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Long.valueOf(nm.substring(index), radix);
result = negative ? Long.valueOf(-result.longValue()) : result;
} catch (NumberFormatException e) {
// If number is Long.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Long.valueOf(constant, radix);
}
return result;
}
/**
*
*/
private final long value;
/**
*
*/
public Long(long value) {
this.value = value;
}
/**
* 将string采用十进制实例一个Long
*/
public Long(String s) throws NumberFormatException {
this.value = parseLong(s, 10);
}
/**
*
*/
public byte byteValue() {
return (byte)value;
}
/**
*
*/
public short shortValue() {
return (short)value;
}
/**
*
*/
public int intValue() {
return (int)value;
}
/**
*
*/
public long longValue() {
return value;
}
/**
*
*/
public float floatValue() {
return (float)value;
}
/**
*
*/
public double doubleValue() {
return (double)value;
}
/**
*
*/
public String toString() {
return toString(value);
}
/**
*
*/
@Override
public int hashCode() {
return Long.hashCode(value);
}
/**
*
*/
public static int hashCode(long value) {
return (int)(value ^ (value >>> 32));
}
/**
*
*/
public boolean equals(Object obj) {
if (obj instanceof Long) {
return value == ((Long)obj).longValue();
}
return false;
}
/**
* 返回系统属性名为nm的值,如果没有相应的值时返回null
*/
public static Long getLong(String nm) {
return getLong(nm, null);
}
/**
* 返回系统属性名为nm的值,没有相应的值时返回值为val的Long对象
*/
public static Long getLong(String nm, long val) {
Long result = Long.getLong(nm, null);
return (result == null) ? Long.valueOf(val) : result;
}
/**
* 返回系统属性名为nm的值,val为如果没有相应的值时返回的默认值
*/
public static Long getLong(String nm, Long val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Long.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
}
/**
* 比较两个Long值的大小,如果
* 本>anotherLong 返回1
* 本==anotherLong 返回0
* 本<anotherLong 返回1
*/
public int compareTo(Long anotherLong) {
return compare(this.value, anotherLong.value);
}
/**
* 比较两个long值的大小,如果
* x>y 返回1
* x==y 返回0
* x<y 返回1
*/
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
/**
* 无符号比较x和y,在这个方法里,负数永远比非负数大,负数中-1最大
*/
public static int compareUnsigned(long x, long y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
/**
* 先转为无符号的Long,再相除
* 当dividor为负数时,如果dividend>divisor返回1,dividend<=divisor时返回0
*/
public static long divideUnsigned(long dividend, long divisor) {
if (divisor < 0L) { // signed comparison
// Answer must be 0 or 1 depending on relative magnitude
// of dividend and divisor.
return (compareUnsigned(dividend, divisor)) < 0 ? 0L :1L;
}
if (dividend > 0) // Both inputs non-negative
return dividend/divisor;
else {
/*
* For simple code, leveraging BigInteger. Longer and faster
* code written directly in terms of operations on longs is
* possible; see "Hacker's Delight" for divide and remainder
* algorithms.
*/
return toUnsignedBigInteger(dividend).
divide(toUnsignedBigInteger(divisor)).longValue();
}
}
/**
* 返回无符号余数,将dividend除以divisor,其中每个参数和结果被解释为无符号值。
*/
public static long remainderUnsigned(long dividend, long divisor) {
if (dividend > 0 && divisor > 0) { // signed comparisons
return dividend % divisor;
} else {
if (compareUnsigned(dividend, divisor) < 0) // Avoid explicit check for 0 divisor
return dividend;
else
return toUnsignedBigInteger(dividend).
remainder(toUnsignedBigInteger(divisor)).longValue();
}
}
// Bit Twiddling
/**
*
*/
@Native public static final int SIZE = 64;
/**
*
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
* 取到long值二进制中最高位,且将其他位取为0后,返回该二进制的long值
* 例如111的二进制1101111,返回1000000
* i |= j 相当于 i = i | j
*/
public static long highestOneBit(long i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
i |= (i >> 32);
return i - (i >>> 1);
}
/**
* 取得long值二进制中最低位的1,且将其他位取为0后,返回改二进制的long值
* 例如110的二进制1101110为返回0000010,
* 其中-110的二进制为11111111111111111111111110010010
* 根据补码规则,负数的二进制为正数二进制取反之后加1
*/
public static long lowestOneBit(long i) {
// HD, Section 2-1
return i & -i;
}
/**
* 返回在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前的零位的数量
* 例如00000000 00000000 011111111 111111111返回16
* 符号位不包含
* 如果值为零,则返回 64
*/
public static int numberOfLeadingZeros(long i) {
// HD, Figure 5-6
if (i == 0)
return 64;
int n = 1;
int x = (int)(i >>> 32);
if (x == 0) { n += 32; x = (int)i; }
if (x >>> 16 == 0) { n += 16; x <<= 16; }
if (x >>> 24 == 0) { n += 8; x <<= 8; }
if (x >>> 28 == 0) { n += 4; x <<= 4; }
if (x >>> 30 == 0) { n += 2; x <<= 2; }
n -= x >>> 31;
return n;
}
/**
* 返回在指定 long 值的二进制补码表示形式中最低位(最右边)的 1 位之后的零位的数量。
* 如果值为零,则返回 64
*/
public static int numberOfTrailingZeros(long i) {
// HD, Figure 5-14
int x, y;
if (i == 0) return 64;
int n = 63;
y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
y = x <<16; if (y != 0) { n = n -16; x = y; }
y = x << 8; if (y != 0) { n = n - 8; x = y; }
y = x << 4; if (y != 0) { n = n - 4; x = y; }
y = x << 2; if (y != 0) { n = n - 2; x = y; }
return n - ((x << 1) >>> 31);
}
/**
* 返回指定 long 值的二进制补码表示形式的 1的位的数量。
*/
public static int bitCount(long i) {
// HD, Figure 5-14
i = i - ((i >>> 1) & 0x5555555555555555L);
i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L);
i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
i = i + (i >>> 8);
i = i + (i >>> 16);
i = i + (i >>> 32);
return (int)i & 0x7f;
}
/**
* 返回根据指定的位数循环左移指定的 long 值的二进制补码表示形式而得到的值。
* (位是从左边(即高位)移出,从右边(即低位)再进入),(符号位也在移的位中)
* 例如1280000001的二进制为:01001100 01001011 01000000 00000001
* 结果为:01001011 01000000 00000001 01001100
*
*
* 1280000001 >>> -8的效果如下
* 1280000001的二进制:01001100010010110100000000000001
* 1280000001 >>> -8:01001100
*/
public static long rotateLeft(long i, int distance) {
return (i << distance) | (i >>> -distance);
}
/**
* 返回根据指定的位数循环右移指定的 long 值的二进制补码表示形式而得到的值。
* (位是从右边(即低位)移出,从左边(即高位)再进入)
* 例如-1280000001的二进制:10110011101101001011111111111111
* 结果:11111111101100111011010010111111
*
*
* -1280000001 << -8的结果如下
* -1280000001的二进制:10110011101101001011111111111111
* -1280000001 << -8的结果:11111111000000000000000000000000
*/
public static long rotateRight(long i, int distance) {
return (i >>> distance) | (i << -distance);
}
/**
* 返回通过反转指定 long 值的二进制补码表示形式中位的顺序而获得的值。
* 例如:-1280000001的二进制:10110011101101001011111111111111
* 结果的二进制为: 11111111111111010010110111001101
* 即为第一个完全颠倒过来
*/
public static long reverse(long i) {
// HD, Figure 7-1
i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
i = (i << 48) | ((i & 0xffff0000L) << 16) |
((i >>> 16) & 0xffff0000L) | (i >>> 48);
return i;
}
/**
* 返回指定 long 值的符号函数。(如果指定值为负,则返回 -1;如果指定值为零,则返回 0;如果指定的值为正,则返回 1。)
*
*
* >>:带符号右移。正数右移高位补0,负数右移高位补1
* >>>:无符号右移。无论是正数还是负数,高位通通补0
*/
public static int signum(long i) {
// HD, Section 2-7
return (int) ((i >> 63) | (-i >>> 63));
}
/**
* 返回通过反转指定 long 值的二进制补码表示形式中字节的顺序而获得的值。
* 因为一个字节占8位,所以
* 例如:-1280000001的二进制:10110011 10110100 10111111 11111111
* 结果的二进制为 11111111 10111111 10110100 10110011
* 即为每8个一组完全颠倒
*/
public static long reverseBytes(long i) {
i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
return (i << 48) | ((i & 0xffff0000L) << 16) |
((i >>> 16) & 0xffff0000L) | (i >>> 48);
}
/**
*
*/
public static long sum(long a, long b) {
return a + b;
}
/**
*
*/
public static long max(long a, long b) {
return Math.max(a, b);
}
/**
*
*/
public static long min(long a, long b) {
return Math.min(a, b);
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
@Native private static final long serialVersionUID = 4290774380558885855L;
}
Float
package java.lang;
import sun.misc.FloatingDecimal;
import sun.misc.FloatConsts;
import sun.misc.DoubleConsts;
/**
* Float 类在对象中包装一个基本类型 float 的值。Float 类型的对象包含一个 float 类型的字段。
*/
public final class Float extends Number implements Comparable<Float> {
/**
* 保存 float 类型的正无穷大值的常量。
*/
public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
/**
* 保存 float 类型的负无穷大值的常量。
*/
public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
/**
* 保存 float 类型的非数字 (NaN) 值的常量。
*/
public static final float NaN = 0.0f / 0.0f;
/**
* 保存 float 类型的最大正有限值的常量,即 (2-2-23)·2^127。
*/
public static final float MAX_VALUE = 0x1.fffffeP+127f; // 3.4028235e+38f
/**
* 保存 float 类型数据的最小正标准值的常量,即 2^(-126)。
*/
public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f
/**
* 保存 float 类型数据的最小正非零值的常量,即 2^(-149)。
*/
public static final float MIN_VALUE = 0x0.000002P-126f; // 1.4e-45f
/**
* 有限 float 变量可能具有的最大指数。
*/
public static final int MAX_EXPONENT = 127;
/**
* 标准化 float 变量可能具有的最小指数。
*/
public static final int MIN_EXPONENT = -126;
/**
*
*/
public static final int SIZE = 32;
/**
*
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
* 表示基本类型 float 的 Class 实例
*/
@SuppressWarnings("unchecked")
public static final Class<Float> TYPE = (Class<Float>) Class.getPrimitiveClass("float");
/**
* 返回此 Float 对象的字符串表示形式。
*/
public static String toString(float f) {
return FloatingDecimal.toJavaFormatString(f);
}
/**
* 返回 float 参数的十六进制字符串表示形式。
*/
public static String toHexString(float f) {
if (Math.abs(f) < FloatConsts.MIN_NORMAL
&& f != 0.0f ) {// float subnormal
// Adjust exponent to create subnormal double, then
// replace subnormal double exponent with subnormal float
// exponent
String s = Double.toHexString(Math.scalb((double)f,
/* -1022+126 */
DoubleConsts.MIN_EXPONENT-
FloatConsts.MIN_EXPONENT));
return s.replaceFirst("p-1022$", "p-126");
}
else // double string will be the same as float string
return Double.toHexString(f);
}
/**
* 返回参数字符串 s 表示的 float 值的 Float 对象。
*/
public static Float valueOf(String s) throws NumberFormatException {
return new Float(parseFloat(s));
}
/**
* 返回表示指定的 float 值的 Float 实例。
*/
public static Float valueOf(float f) {
return new Float(f);
}
/**
* 将字符串s转换为float值
*/
public static float parseFloat(String s) throws NumberFormatException {
return FloatingDecimal.parseFloat(s);
}
/**
* 如果指定的数是一个非数字 (NaN) 值,则返回 true,否则返回 false。
*/
public static boolean isNaN(float v) {
return (v != v);
}
/**
* 如果指定数的数值是无穷大,则返回 true,否则返回 false。
*/
public static boolean isInfinite(float v) {
return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY);
}
/**
* 如果参数是有限浮点值,则返回true ; 否则返回false (对于NaN和无穷大参数)。
*/
public static boolean isFinite(float f) {
return Math.abs(f) <= FloatConsts.MAX_VALUE;
}
/**
*
*/
private final float value;
/**
*
*/
public Float(float value) {
this.value = value;
}
/**
*
*/
public Float(double value) {
this.value = (float)value;
}
/**
*
*/
public Float(String s) throws NumberFormatException {
value = parseFloat(s);
}
/**
* 如果此 Float 值是一个非数字 (NaN) 值,则返回 true,否则返回 false。
*/
public boolean isNaN() {
return isNaN(value);
}
/**
* 如果此 Float 值的大小是无穷大,则返回 true,否则返回 false。
*/
public boolean isInfinite() {
return isInfinite(value);
}
/**
* 返回此 Float 对象的字符串表示形式。对象的 float 值被转换为一个 String
*/
public String toString() {
return Float.toString(value);
}
/**
*
*/
public byte byteValue() {
return (byte)value;
}
/**
*
*/
public short shortValue() {
return (short)value;
}
/**
*
*/
public int intValue() {
return (int)value;
}
/**
*
*/
public long longValue() {
return (long)value;
}
/**
*
*/
public float floatValue() {
return value;
}
/**
*
*/
public double doubleValue() {
return (double)value;
}
/**
*
*
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
return Float.hashCode(value);
}
/**
*
*/
public static int hashCode(float value) {
return floatToIntBits(value);
}
/**
*
*/
public boolean equals(Object obj) {
return (obj instanceof Float)
&& (floatToIntBits(((Float)obj).value) == floatToIntBits(value));
}
/**
* 根据 IEEE 754 浮点“单一格式”位布局,返回指定浮点值的表示形式。
*
* 第 31 位(掩码 0x80000000 选定的位)表示浮点数的符号。
* 第 30-23 位(掩码 0x7f800000 选定的位)表示指数。
* 第 22-0 位(掩码 0x007fffff 选定的位)表示浮点数的有效位数(有时也称为尾数)。
* 即32位浮点数在计算机中二进制存储形式共三部分:S(1位,符号) E(8位,阶码) M(23位,尾数)
*
* Float.floatToIntBits(2.125f)按照如下方式计算:
* 2.125D=10.001B=1.0001*2^1B 指数e=1
* S=0-->正数 E=1+127=131D=10000000B-->真实指数e变成阶码E时需加127 M=0001B
* 则32位2进制存储形式为:0 10000000 00010000000000000000000
* 转换成10进制即1074266112即该方法的返回值
*/
public static int floatToIntBits(float value) {
int result = floatToRawIntBits(value);
// Check for NaN based on values of bit fields, maximum
// exponent and nonzero significand.
if ( ((result & FloatConsts.EXP_BIT_MASK) ==
FloatConsts.EXP_BIT_MASK) &&
(result & FloatConsts.SIGNIF_BIT_MASK) != 0)
result = 0x7fc00000;
return result;
}
/**
*
*/
public static native int floatToRawIntBits(float value);
/**
* 返回对应于给定位表示形式的 float 值。根据 IEEE 754 浮点“单一格式”位布局,该参数被视为浮点值表示形式。
* 即方法floatToIntBits的反方法
*/
public static native float intBitsToFloat(int bits);
/**
* 比较两个Float值的大小,如果
* 本>anotherFloat 返回1
* 本==anotherFloat 返回0
* 本<anotherFloat 返回1
*
* 此方法认为 Float.NaN 等于其自身(但使用==判断时为false),且大于其他所有 float 值(包括 Float.POSITIVE_INFINITY)。
* 此方法认为 0.0f 大于 -0.0f。
*/
public int compareTo(Float anotherFloat) {
return Float.compare(value, anotherFloat.value);
}
/**
* 比较两个long值的大小,如果
* x>y 返回1
* x==y 返回0(这时候是通过根据 IEEE 754 浮点“单一格式”位布局来判断位是否相同得到的)
* x<y 返回1
*
* 此方法认为 Float.NaN 等于其自身(但使用==判断时为false),且大于其他所有 float 值(包括 Float.POSITIVE_INFINITY)。
* 此方法认为 0.0f 大于 -0.0f。
*/
public static int compare(float f1, float f2) {
if (f1 < f2)
return -1; // Neither val is NaN, thisVal is smaller
if (f1 > f2)
return 1; // Neither val is NaN, thisVal is larger
// Cannot use floatToRawIntBits because of possibility of NaNs.
int thisBits = Float.floatToIntBits(f1);
int anotherBits = Float.floatToIntBits(f2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}
/**
*
*/
public static float sum(float a, float b) {
return a + b;
}
/**
*
*/
public static float max(float a, float b) {
return Math.max(a, b);
}
/**
*
*/
public static float min(float a, float b) {
return Math.min(a, b);
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -2671257302660747028L;
}
Double
package java.lang;
import sun.misc.FloatingDecimal;
import sun.misc.FpUtils;
import sun.misc.DoubleConsts;
/**
* IEEE 754 浮点“单一格式”位布局:
* 类型 符号位(S) 指数位(E) 尾数位(M)
* float 1位(第31位) 8位(30位——23位) 23位(22位——0位)
* double 1位(第63位) 11位(62位——52位) 52位(51位——0位)
*
*
* 由于float的尾数位为23位,1/2^23=1/8388608=0.000000119;所以float的精确度为小数点后7-8位
* 而对于double,1/2^52=2.220*10^(-16);所以double的精确度为小数点后16-17位,这也是double叫双精度的原因
*
* 那么一个十进制的小树怎么转换为浮点数呢?
* 以78.375f为例
* 首先78用除2得余数的方法转为二进制为1001110,
* 具体过程为:78/2=39余0,所以最后一位为0, 39/2=19余1,所以倒数第二位为1,依次计算可得;
* 小数用乘2取整数的方法转为二进制为0.011,
* 具体过程为:0.375*2=0.75,整数为0,所以小数点后第一位为0, 0.75*2=1.5,所以小数点后第二位为1,同时1.5要减去1,
* 然后0.5*2=1.0,所以小数点后第三位为1;由计算过程可知,实际数字转为浮点数有精度损失,且浮点数所描述的数字不是连续的
*
* 将整数部分得到的二进制数和小数部分得到的二进制合在一起得到1001110.011=1.001110011*2^(6)
* 其中6是存到指数位里的,小数点后的001110011是存到尾数位里的,
* 整数1因为一直都会是1所以省略了(如果不是78.375而是0.375则上面这步小数点往后移,因为指数位不能为0)
*
* 于是:78.375D=1001110.011B=1.001110011*2^6B 指数e=6
* S=0-->正数 E=6+127=131D=10000101B-->真实指数e变成阶码E时需加127 M=001110011B
* 则32位2进制存储形式为:0 10000101 00111001100000000000000
* 转换成10进制即1117569024即IEEE 754 浮点“单一格式”位布局十进制的值,即方法floatToIntBits的返回值
* Double的机制一样,只是位数不相同,阶码加1023
*
*
* 由于在标准中规定了当指数位为全0或全1的时候,浮点数为非正规形式
* 因此float的正值范围为2^(-126-23)——2^(127+1),其中-126是因为-127的二进制全为1所以负数最小只能取到-126-23为尾数位的精度,+1是因为尾数位可以很接近1加上整数1导致接近2,
* 于是同样的道理double的正值范围为2^(-1022-52)——2^(1023+1)
*/
public final class Double extends Number implements Comparable<Double> {
/**
* 保存 double 类型的正无穷大值的常量。
*/
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
/**
* 保存 double 类型的负无穷大值的常量。
*/
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
/**
* 保存 double 类型的 NaN 值的常量。
*/
public static final double NaN = 0.0d / 0.0;
/**
* 保存 double 类型的最大正有限值的常量,最大正有限值为 (2-2-52)·21023。
*/
public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308
/**
* 保存 double 类型的最小正标准值的常量,最小正标准值为 2-1022。
*/
public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308
/**
* 保存 double 类型的最小正非零值的常量,最小正非零值为 2-1074。
*/
public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324
/**
* 有限 double 变量可能具有的最大指数。
*/
public static final int MAX_EXPONENT = 1023;
/**
* 有限 double 变量可能具有的最小指数。
*/
public static final int MIN_EXPONENT = -1022;
/**
*
*/
public static final int SIZE = 64;
/**
*
*/
public static final int BYTES = SIZE / Byte.SIZE;
/**
* 表示基本类型 double 的 Class 实例
*/
@SuppressWarnings("unchecked")
public static final Class<Double> TYPE = (Class<Double>) Class.getPrimitiveClass("double");
/**
* 返回此 Double 对象的字符串表示形式。
*/
public static String toString(double d) {
return FloatingDecimal.toJavaFormatString(d);
}
/**
* 返回 double 参数的十六进制字符串表示形式。
*/
public static String toHexString(double d) {
/*
* Modeled after the "a" conversion specifier in C99, section
* 7.19.6.1; however, the output of this method is more
* tightly specified.
*/
if (!isFinite(d) )
// For infinity and NaN, use the decimal output.
return Double.toString(d);
else {
// Initialized to maximum size of output.
StringBuilder answer = new StringBuilder(24);
if (Math.copySign(1.0, d) == -1.0) // value is negative,
answer.append("-"); // so append sign info
answer.append("0x");
d = Math.abs(d);
if(d == 0.0) {
answer.append("0.0p0");
} else {
boolean subnormal = (d < DoubleConsts.MIN_NORMAL);
// Isolate significand bits and OR in a high-order bit
// so that the string representation has a known
// length.
long signifBits = (Double.doubleToLongBits(d)
& DoubleConsts.SIGNIF_BIT_MASK) |
0x1000000000000000L;
// Subnormal values have a 0 implicit bit; normal
// values have a 1 implicit bit.
answer.append(subnormal ? "0." : "1.");
// Isolate the low-order 13 digits of the hex
// representation. If all the digits are zero,
// replace with a single 0; otherwise, remove all
// trailing zeros.
String signif = Long.toHexString(signifBits).substring(3,16);
answer.append(signif.equals("0000000000000") ? // 13 zeros
"0":
signif.replaceFirst("0{1,12}$", ""));
answer.append('p');
// If the value is subnormal, use the E_min exponent
// value for double; otherwise, extract and report d's
// exponent (the representation of a subnormal uses
// E_min -1).
answer.append(subnormal ?
DoubleConsts.MIN_EXPONENT:
Math.getExponent(d));
}
return answer.toString();
}
}
/**
* 返回值为参数字符串s表示的double相同的Double 对象。
*/
public static Double valueOf(String s) throws NumberFormatException {
return new Double(parseDouble(s));
}
/**
* 返回表示指定的 double 值的 Double 实例
*/
public static Double valueOf(double d) {
return new Double(d);
}
/**
* 将字符串s转为double
*/
public static double parseDouble(String s) throws NumberFormatException {
return FloatingDecimal.parseDouble(s);
}
/**
* 如果指定的数是一个 NaN 值,则返回 true;否则返回 false。
*/
public static boolean isNaN(double v) {
return (v != v);
}
/**
* 如果指定数在数值上为无穷大,则返回 true;否则返回 false。
*/
public static boolean isInfinite(double v) {
return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY);
}
/**
* 如果此 Double 值是非数字(NaN)值,则返回 true;否则返回 false。
*/
public static boolean isFinite(double d) {
return Math.abs(d) <= DoubleConsts.MAX_VALUE;
}
/**
*
*/
private final double value;
/**
*
*/
public Double(double value) {
this.value = value;
}
/**
*
*/
public Double(String s) throws NumberFormatException {
value = parseDouble(s);
}
/**
* 如果此 Double 值是非数字(NaN)值,则返回 true;否则返回 false。
*/
public boolean isNaN() {
return isNaN(value);
}
/**
* 如果此 Double 值在数值上为无穷大,则返回 true;否则返回 false。
*/
public boolean isInfinite() {
return isInfinite(value);
}
/**
*
*/
public String toString() {
return toString(value);
}
/**
*
*/
public byte byteValue() {
return (byte)value;
}
/**
*
*/
public short shortValue() {
return (short)value;
}
/**
*
*/
public int intValue() {
return (int)value;
}
/**
*
*/
public long longValue() {
return (long)value;
}
/**
*
*/
public float floatValue() {
return (float)value;
}
/**
*
*/
public double doubleValue() {
return value;
}
/**
*
*/
@Override
public int hashCode() {
return Double.hashCode(value);
}
/**
*
*/
public static int hashCode(double value) {
long bits = doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
/**
*
*/
public boolean equals(Object obj) {
return (obj instanceof Double)
&& (doubleToLongBits(((Double)obj).value) ==
doubleToLongBits(value));
}
/**
* 类似float.floatToIntBits方法
*/
public static long doubleToLongBits(double value) {
long result = doubleToRawLongBits(value);
// Check for NaN based on values of bit fields, maximum
// exponent and nonzero significand.
if ( ((result & DoubleConsts.EXP_BIT_MASK) ==
DoubleConsts.EXP_BIT_MASK) &&
(result & DoubleConsts.SIGNIF_BIT_MASK) != 0L)
result = 0x7ff8000000000000L;
return result;
}
/**
*
*/
public static native long doubleToRawLongBits(double value);
/**
* 返回对应于给定位表示形式的 double 值。根据 IEEE 754 浮点“双精度格式”位布局,参数被视为浮点值表示形式。
* 即方法doubleToLongBits的反方法
*/
public static native double longBitsToDouble(long bits);
/**
* 比较两个Double值的大小,如果
* 本>anotherDouble 返回1
* 本==anotherDouble 返回0
* 本<anotherDouble 返回1
*
* 此方法认为 anotherDouble.NaN 等于其自身(但使用==判断时为false),且大于其他所有 double 值(包括 Double.POSITIVE_INFINITY)。
* 此方法认为 0.0d 大于 -0.0d。
*/
public int compareTo(Double anotherDouble) {
return Double.compare(value, anotherDouble.value);
}
/**
* 比较两个Double值的大小,如果
* 本>anotherDouble 返回1
* 本==anotherDouble 返回0
* 本<anotherDouble 返回1
*
* 此方法认为 anotherDouble.NaN 等于其自身(但使用==判断时为false),且大于其他所有 double 值(包括 Double.POSITIVE_INFINITY)。
* 此方法认为 0.0d 大于 -0.0d。
*/
public static int compare(double d1, double d2) {
if (d1 < d2)
return -1; // Neither val is NaN, thisVal is smaller
if (d1 > d2)
return 1; // Neither val is NaN, thisVal is larger
// Cannot use doubleToRawLongBits because of possibility of NaNs.
long thisBits = Double.doubleToLongBits(d1);
long anotherBits = Double.doubleToLongBits(d2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}
/**
*
*/
public static double sum(double a, double b) {
return a + b;
}
/**
*
*/
public static double max(double a, double b) {
return Math.max(a, b);
}
/**
*
*/
public static double min(double a, double b) {
return Math.min(a, b);
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -9172774392245257468L;
}
Math
package java.lang;
import java.util.Random;
import sun.misc.FloatConsts;
import sun.misc.DoubleConsts;
/**
* Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
* 与 StrictMath 类的某些数学方法不同,并非 Math 类所有等价函数的实现都定义为返回逐位相同的结果。此类在不需要严格重复的地方可以得到更好的执行。
*
*/
public final class Math {
/**
* 私有构造方法
*/
private Math() {}
/**
* 常数e
*/
public static final double E = 2.7182818284590452354;
/**
* 常数π
*/
public static final double PI = 3.14159265358979323846;
/**
* sin(x)
*/
public static double sin(double a) {
return StrictMath.sin(a); // default impl. delegates to StrictMath
}
/**
* cos(x)
*/
public static double cos(double a) {
return StrictMath.cos(a); // default impl. delegates to StrictMath
}
/**
* tan(x)
*/
public static double tan(double a) {
return StrictMath.tan(a); // default impl. delegates to StrictMath
}
/**
* arcsin(x)
*/
public static double asin(double a) {
return StrictMath.asin(a); // default impl. delegates to StrictMath
}
/**
* arccos(x)
*/
public static double acos(double a) {
return StrictMath.acos(a); // default impl. delegates to StrictMath
}
/**
* arctan(x)
*/
public static double atan(double a) {
return StrictMath.atan(a); // default impl. delegates to StrictMath
}
/**
* 角度转弧度
*/
public static double toRadians(double angdeg) {
return angdeg / 180.0 * PI;
}
/**
* 弧度转角度
*/
public static double toDegrees(double angrad) {
return angrad * 180.0 / PI;
}
/**
* 计算e^(x)
*/
public static double exp(double a) {
return StrictMath.exp(a); // default impl. delegates to StrictMath
}
/**
* 计算ln(x)
*/
public static double log(double a) {
return StrictMath.log(a); // default impl. delegates to StrictMath
}
/**
* 计算log10(x)
*/
public static double log10(double a) {
return StrictMath.log10(a); // default impl. delegates to StrictMath
}
/**
* 算数平方根
*/
public static double sqrt(double a) {
return StrictMath.sqrt(a); // default impl. delegates to StrictMath
// Note that hardware sqrt instructions
// frequently can be directly used by JITs
// and should be much faster than doing
// Math.sqrt in software.
}
/**
* 计算立方根
*/
public static double cbrt(double a) {
return StrictMath.cbrt(a);
}
/**
* 按照 IEEE 754 标准的规定,对两个参数进行余数运算。
* 余数的算术值等于 f1 - f2 × n,其中 n 是最接近商 f1/f2 准确算术值的整数,如果两个整数都同样接近 f1/f2,那么 n 是其中的偶数。
*
* 如果余数是 0,那么它的符号与第一个参数的符号相同。特殊情况如下:
* 如果两个参数都为 NaN,或者第一个参数为无穷大,或者第二个参数为正 0 或负 0,那么结果为 NaN。
* 如果第一个参数为有限值,第二个参数为无穷大,那么结果与第一个参数相同。
*
* 例如:Math.IEEEremainder(10.25, 4.1)
* 本来10.25/4.1=2.5,取偶数为2,但是由于底层是用二进制计算的实际得到的结果略大于2.5,所以实际n=3,
* 所以余数=10.25-4.1*3=-2.05
*
*/
public static double IEEEremainder(double f1, double f2) {
return StrictMath.IEEEremainder(f1, f2); // delegate to StrictMath
}
/**
* 返回数轴右边最接近参数的整数,特殊情况如下:
* 如果参数值已经等于某个整数,那么结果与该参数相同。
* 如果参数为 NaN、无穷大、正 0 或负 0,那么结果与参数相同。
* 如果参数值小于 0,但是大于 -1.0,那么结果为负 0。
* 注意,Math.ceil(x) 的值与 -Math.floor(-x) 的值完全相同。
*/
public static double ceil(double a) {
return StrictMath.ceil(a); // default impl. delegates to StrictMath
}
/**
* 返回数轴左边最接近参数的整数。特殊情况如下:
* 如果参数值已经等于某个整数,那么结果与该参数相同。
* 如果参数为 NaN、无穷大、正 0 或负 0,那么结果与参数相同。
*/
public static double floor(double a) {
return StrictMath.floor(a); // default impl. delegates to StrictMath
}
/**
* 返回数轴上最接近参数的整数。如果有两个参数和整数的距离同样近,那么结果取偶数。特殊情况如下:
* 如果参数值已经是整数,那么结果与参数相同。
* 如果参数为 NaN、无穷大、正 0 或负 0,那么结果与参数相同。
*
*/
public static double rint(double a) {
return StrictMath.rint(a); // default impl. delegates to StrictMath
}
/**
* 将矩形坐标 (x, y) 转换成极坐标 (r, theta),返回所得角 theta。该方法通过计算 y/x 的反正切值来计算相角 theta,范围为从 -pi 到 pi。特殊情况如下:
*
* 如果任一参数为 NaN,那么结果为 NaN。
* 如果第一个参数为正 0,第二个参数为正数;或者第一个参数为正的有限值,第二个参数为正无穷大,那么结果为正 0。
* 如果第一个参数为负 0,第二个参数为正数;或者第一个参数为负的有限值,第二个参数为正无穷大,那么结果为负 0。
* 如果第一个参数为正 0,第二个参数为负数;或者第一个参数为正的有限值,第二个参数为负无穷大,那么结果为最接近 pi 的 double 值。
* 如果第一个参数为负 0,第二个参数为负数;或者第一个参数为负的有限值,第二个参数为负无穷大,那么结果为最接近 pi 的 double 值。
* 如果第一个参数为正数,第二个参数为正 0 或负 0;或者第一个参数为正无穷大,第二个参数为有限值,那么结果为最接近 pi/2 的 double 值。
* 如果第一个参数为负数,第二个参数为正 0 或负 0;或者第一个参数为负无穷大,第二个参数为有限值,那么结果为最接近 -pi/2 的 double 值。
* 如果两个参数都为正无穷大,那么结果为最接近 pi/4 的 double 值。
* 如果第一个参数为正无穷大,第二个参数为负无穷大,那么结果为最接近 3*pi/4 的 double 值。
* 如果第一个参数为负无穷大,第二个参数为正无穷大,那么结果为最接近 -pi/4 的 double 值。
* 如果两个参数都为负无穷大,那么结果为最接近 -3*pi/4 的 double 值。
*/
public static double atan2(double y, double x) {
return StrictMath.atan2(y, x); // default impl. delegates to StrictMath
}
/**
* 返回第一个参数的第二个参数次幂的值即a^b。
*/
public static double pow(double a, double b) {
return StrictMath.pow(a, b); // default impl. delegates to StrictMath
}
/**
* 返回最接近参数的 int。
* 结果类似于a先加上 1/2f,然后调用 floor方法,并将所得结果强制转换为 int 类型。
* 换句话说,结果等于以下表达式的值:
* (int)Math.floor(a + 0.5f)
* 特殊情况如下:
* 如果参数为 NaN,那么结果为 0。
* 如果结果为负无穷大或任何小于等于 Integer.MIN_VALUE 的值,那么结果等于 Integer.MIN_VALUE 的值。
* 如果参数为正无穷大或任何大于等于 Integer.MAX_VALUE 的值,那么结果等于 Integer.MAX_VALUE 的值。
*
*/
public static int round(float a) {
int intBits = Float.floatToRawIntBits(a);
int biasedExp = (intBits & FloatConsts.EXP_BIT_MASK)
>> (FloatConsts.SIGNIFICAND_WIDTH - 1);
int shift = (FloatConsts.SIGNIFICAND_WIDTH - 2
+ FloatConsts.EXP_BIAS) - biasedExp;
if ((shift & -32) == 0) { // shift >= 0 && shift < 32
// a is a finite number such that pow(2,-32) <= ulp(a) < 1
int r = ((intBits & FloatConsts.SIGNIF_BIT_MASK)
| (FloatConsts.SIGNIF_BIT_MASK + 1));
if (intBits < 0) {
r = -r;
}
// In the comments below each Java expression evaluates to the value
// the corresponding mathematical expression:
// (r) evaluates to a / ulp(a)
// (r >> shift) evaluates to floor(a * 2)
// ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2)
// (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2)
return ((r >> shift) + 1) >> 1;
} else {
// a is either
// - a finite number with abs(a) < exp(2,FloatConsts.SIGNIFICAND_WIDTH-32) < 1/2
// - a finite number with ulp(a) >= 1 and hence a is a mathematical integer
// - an infinity or NaN
return (int) a;
}
}
/**
* 返回最接近参数的 long。
* 结果类似于a先加上 1/2d,然后调用 floor方法,并将所得结果强制转换为 long 类型。
* 换句话说,结果等于以下表达式的值:
* (long)Math.floor(a + 0.5d)
*
* 特殊情况如下:
* 如果参数为 NaN,那么结果为 0。
* 如果结果为负无穷大或任何小于等于 Long.MIN_VALUE 的值,那么结果等于 Long.MIN_VALUE 的值。
* 如果参数为正无穷大或任何大于等于 Long.MAX_VALUE 的值,那么结果等于 Long.MAX_VALUE 的值。
*
*/
public static long round(double a) {
long longBits = Double.doubleToRawLongBits(a);
long biasedExp = (longBits & DoubleConsts.EXP_BIT_MASK)
>> (DoubleConsts.SIGNIFICAND_WIDTH - 1);
long shift = (DoubleConsts.SIGNIFICAND_WIDTH - 2
+ DoubleConsts.EXP_BIAS) - biasedExp;
if ((shift & -64) == 0) { // shift >= 0 && shift < 64
// a is a finite number such that pow(2,-64) <= ulp(a) < 1
long r = ((longBits & DoubleConsts.SIGNIF_BIT_MASK)
| (DoubleConsts.SIGNIF_BIT_MASK + 1));
if (longBits < 0) {
r = -r;
}
// In the comments below each Java expression evaluates to the value
// the corresponding mathematical expression:
// (r) evaluates to a / ulp(a)
// (r >> shift) evaluates to floor(a * 2)
// ((r >> shift) + 1) evaluates to floor((a + 1/2) * 2)
// (((r >> shift) + 1) >> 1) evaluates to floor(a + 1/2)
return ((r >> shift) + 1) >> 1;
} else {
// a is either
// - a finite number with abs(a) < exp(2,DoubleConsts.SIGNIFICAND_WIDTH-64) < 1/2
// - a finite number with ulp(a) >= 1 and hence a is a mathematical integer
// - an infinity or NaN
return (long) a;
}
}
private static final class RandomNumberGeneratorHolder {
static final Random randomNumberGenerator = new Random();
}
/**
* 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。返回值是一个伪随机选择的数,在该范围内(近似)均匀分布。
*
* 此方法是完全同步的,可允许多个线程使用而不出现错误。
* 但是,如果许多线程需要以极高的速率生成伪随机数,那么这可能会减少每个线程对拥有自己伪随机数生成器的争用。
*/
public static double random() {
return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}
/**
* 返回x+y的和,如果结果溢出int,则抛出异常 。
*/
public static int addExact(int x, int y) {
int r = x + y;
// HD 2-12 Overflow iff both arguments have the opposite sign of the result
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
/**
* 返回x+y的和,如果结果溢出long,则抛出异常 。
*
* 两个数的异或算法一般情况下相当于两数想减,然后取绝对值,但是如果超出范围就只能是负了
*/
public static long addExact(long x, long y) {
long r = x + y;
// HD 2-12 Overflow iff both arguments have the opposite sign of the result
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("long overflow");
}
return r;
}
/**
* 返回x-y的差,如果结果溢出int,则抛出 异常 。
*/
public static int subtractExact(int x, int y) {
int r = x - y;
// HD 2-12 Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if (((x ^ y) & (x ^ r)) < 0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
/**
* 返回x-y的差,如果结果溢出long,则抛出 异常 。
*/
public static long subtractExact(long x, long y) {
long r = x - y;
// HD 2-12 Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if (((x ^ y) & (x ^ r)) < 0) {
throw new ArithmeticException("long overflow");
}
return r;
}
/**
* 返回x*y的积,如果结果溢出int,则抛出 异常 。
*/
public static int multiplyExact(int x, int y) {
long r = (long)x * (long)y;
if ((int)r != r) {
throw new ArithmeticException("integer overflow");
}
return (int)r;
}
/**
* 返回x*y的积,如果结果溢出long,则抛出 异常 。
*/
public static long multiplyExact(long x, long y) {
long r = x * y;
long ax = Math.abs(x);
long ay = Math.abs(y);
if (((ax | ay) >>> 31 != 0)) {
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
if (((y != 0) && (r / y != x)) ||
(x == Long.MIN_VALUE && y == -1)) {
throw new ArithmeticException("long overflow");
}
}
return r;
}
/**
* 返回a+1的值,如果结果溢出int,则抛出 异常 。
*/
public static int incrementExact(int a) {
if (a == Integer.MAX_VALUE) {
throw new ArithmeticException("integer overflow");
}
return a + 1;
}
/**
* 返回a+1的值,如果结果溢出long,则抛出 异常 。
*/
public static long incrementExact(long a) {
if (a == Long.MAX_VALUE) {
throw new ArithmeticException("long overflow");
}
return a + 1L;
}
/**
* 返回a-1的值,如果结果溢出int,则抛出 异常 。
*/
public static int decrementExact(int a) {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("integer overflow");
}
return a - 1;
}
/**
* 返回a-1的值,如果结果溢出long,则抛出 异常 。
*/
public static long decrementExact(long a) {
if (a == Long.MIN_VALUE) {
throw new ArithmeticException("long overflow");
}
return a - 1L;
}
/**
* 返回参数的相反数,如果结果溢出int,则抛出 异常 。
*/
public static int negateExact(int a) {
if (a == Integer.MIN_VALUE) {
throw new ArithmeticException("integer overflow");
}
return -a;
}
/**
* 返回参数的相反数,如果结果溢出long,则抛出 异常 。
*/
public static long negateExact(long a) {
if (a == Long.MIN_VALUE) {
throw new ArithmeticException("long overflow");
}
return -a;
}
/**
* 将long值转为int,如果value的值大于int的最大值,则抛出异常
* 即该方法只能讲value值小于int最大值的long转为int
*/
public static int toIntExact(long value) {
if ((int)value != value) {
throw new ArithmeticException("integer overflow");
}
return (int)value;
}
/**
* 返回数轴左边最接近代数商(x/y)的int值。
* 有一个特殊情况,如果x为Integer.MIN_VALUE ,y为-1 ,则发生整数溢出,结果等于Integer.MIN_VALUE 。
*
* 正常整数除法(a/b)返回最接近零的整数。
*
* 如果参数的符号相同,那么floorDiv和/操作符的结果是一样的。
* 例如, floorDiv(4, 3) == 1和(4 / 3) == 1 。
* 如果参数的符号不同,则商为负, floorDiv返回数轴左边最接近代数商的int值, /操作符返回最接近零的整数。
* 例如, floorDiv(-4, 3) == -2 ,而(-4 / 3) == -1 。
*
*/
public static int floorDiv(int x, int y) {
int r = x / y;
// if the signs are different and modulo not zero, round down
if ((x ^ y) < 0 && (r * y != x)) {
r--;
}
return r;
}
/**
* 返回数轴左边最接近代数商(x/y)的long值。
* 有一个特殊情况,如果x为Long.MIN_VALUE ,y为-1 ,则发生整数溢出,结果等于Long.MIN_VALUE 。
*
* 正常整数除法(a/b)返回最接近零的整数。
*
* 如果参数的符号相同,那么floorDiv和/操作符的结果是一样的。
* 例如, floorDiv(4, 3) == 1和(4 / 3) == 1 。
* 如果参数的符号不同,则商为负, floorDiv返回数轴左边最接近代数商的int值, /操作符返回最接近零的整数。
* 例如, floorDiv(-4, 3) == -2 ,而(-4 / 3) == -1 。
*/
public static long floorDiv(long x, long y) {
long r = x / y;
// if the signs are different and modulo not zero, round down
if ((x ^ y) < 0 && (r * y != x)) {
r--;
}
return r;
}
/**
* 返回(x - floorDiv(x, y) * y)
*/
public static int floorMod(int x, int y) {
int r = x - floorDiv(x, y) * y;
return r;
}
/**
* 返回(x - floorDiv(x, y) * y)
*/
public static long floorMod(long x, long y) {
return x - floorDiv(x, y) * y;
}
/**
* 返回 int 值的绝对值
*/
public static int abs(int a) {
return (a < 0) ? -a : a;
}
/**
* 返回 long 值的绝对值
*/
public static long abs(long a) {
return (a < 0) ? -a : a;
}
/**
* 返回 float 值的绝对值
*/
public static float abs(float a) {
return (a <= 0.0F) ? 0.0F - a : a;
}
/**
* 返回 double 值的绝对值
*/
public static double abs(double a) {
return (a <= 0.0D) ? 0.0D - a : a;
}
/**
* 返回两个int值中的最大值
*/
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
/**
* 返回两个long值中的最大值
*/
public static long max(long a, long b) {
return (a >= b) ? a : b;
}
// Use raw bit-wise conversions on guaranteed non-NaN arguments.
private static long negativeZeroFloatBits = Float.floatToRawIntBits(-0.0f);
private static long negativeZeroDoubleBits = Double.doubleToRawLongBits(-0.0d);
/**
* 返回两个float值中的最大值
*/
public static float max(float a, float b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0f) &&
(b == 0.0f) &&
(Float.floatToRawIntBits(a) == negativeZeroFloatBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a >= b) ? a : b;
}
/**
* 返回两个double值中的最大值
*/
public static double max(double a, double b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0d) &&
(b == 0.0d) &&
(Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a >= b) ? a : b;
}
/**
* 返回两个int值中的最小值
*/
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
/**
* 返回两个long值中的最小值
*/
public static long min(long a, long b) {
return (a <= b) ? a : b;
}
/**
* 返回两个float值中的最小值
*/
public static float min(float a, float b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0f) &&
(b == 0.0f) &&
(Float.floatToRawIntBits(b) == negativeZeroFloatBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a <= b) ? a : b;
}
/**
* 返回两个double值中的最小值
*/
public static double min(double a, double b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0d) &&
(b == 0.0d) &&
(Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a <= b) ? a : b;
}
/**
* 返回参数的 ulp 大小。(double 值的 ulp 指此浮点值与下一个数值较大的 double 值之间的正距离)
* 反应在double的存储结构里即令double的尾数位全为0,指数位减去52后转成double值即该方法的返回值
*/
public static double ulp(double d) {
int exp = getExponent(d);
switch(exp) {
case DoubleConsts.MAX_EXPONENT+1: // NaN or infinity
return Math.abs(d);
case DoubleConsts.MIN_EXPONENT-1: // zero or subnormal
return Double.MIN_VALUE;
default:
assert exp <= DoubleConsts.MAX_EXPONENT && exp >= DoubleConsts.MIN_EXPONENT;
// ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x))
exp = exp - (DoubleConsts.SIGNIFICAND_WIDTH-1);
if (exp >= DoubleConsts.MIN_EXPONENT) {
return powerOfTwoD(exp);
}
else {
// return a subnormal result; left shift integer
// representation of Double.MIN_VALUE appropriate
// number of positions
return Double.longBitsToDouble(1L <<
(exp - (DoubleConsts.MIN_EXPONENT - (DoubleConsts.SIGNIFICAND_WIDTH-1)) ));
}
}
}
/**
* 返回参数的 ulp 大小。(float 值的 ulp 指此浮点值与下一个数值较大的 float 值之间的正距离)
* 反应在float的存储结构里即令float的尾数位全为0,指数位减去23后转成float值即该方法的返回值
*/
public static float ulp(float f) {
int exp = getExponent(f);
switch(exp) {
case FloatConsts.MAX_EXPONENT+1: // NaN or infinity
return Math.abs(f);
case FloatConsts.MIN_EXPONENT-1: // zero or subnormal
return FloatConsts.MIN_VALUE;
default:
assert exp <= FloatConsts.MAX_EXPONENT && exp >= FloatConsts.MIN_EXPONENT;
// ulp(x) is usually 2^(SIGNIFICAND_WIDTH-1)*(2^ilogb(x))
exp = exp - (FloatConsts.SIGNIFICAND_WIDTH-1);
if (exp >= FloatConsts.MIN_EXPONENT) {
return powerOfTwoF(exp);
}
else {
// return a subnormal result; left shift integer
// representation of FloatConsts.MIN_VALUE appropriate
// number of positions
return Float.intBitsToFloat(1 <<
(exp - (FloatConsts.MIN_EXPONENT - (FloatConsts.SIGNIFICAND_WIDTH-1)) ));
}
}
}
/**
* 返回参数的符号函数;如果参数为 0,则返回 0;如果参数大于 0,则返回 1.0;如果参数小于 0,则返回 -1.0。
*
* 如果参数为 NaN,那么结果为 NaN。
* 如果参数为正 0 或负 0,那么结果与参数相同。
*/
public static double signum(double d) {
return (d == 0.0 || Double.isNaN(d))?d:copySign(1.0, d);
}
/**
* 返回参数的符号函数;如果参数为 0,则返回 0;如果参数大于 0,则返回 1.0;如果参数小于 0,则返回 -1.0。
*
* 如果参数为 NaN,那么结果为 NaN。
* 如果参数为正 0 或负 0,那么结果与参数相同。
*/
public static float signum(float f) {
return (f == 0.0f || Float.isNaN(f))?f:copySign(1.0f, f);
}
/**
* 返回 double 值的双曲线正弦。x 双曲线正弦的定义是 (e^x - e^(-x))/2
*
* 如果参数为 NaN,那么结果为 NaN。
* 如果参数为无穷大,那么结果为无穷大,符号与参数符号相同。
* 如果参数为 0,那么结果为 0,符号与参数符号相同。
*/
public static double sinh(double x) {
return StrictMath.sinh(x);
}
/**
* 返回 double 值的双曲线余弦。x 的双曲线余弦的定义是 (e^x + e^(-x))/2
*
* 特殊情况如下:
* 如果参数为 NaN,那么结果为 NaN。
* 如果参数为无穷大,那么结果为正无穷大。
* 如果参数为 0,那么结果为 1.0。
*
*/
public static double cosh(double x) {
return StrictMath.cosh(x);
}
/**
* 返回 double 值的双曲线余弦。x 的双曲线正切的定义是 (e^x - e^(-x))/(e^x + e^(-x)),即 sinh(x)/cosh(x)。注意,准确的 tanh 绝对值始终小于 1。
*
* 特殊情况如下:
* 如果参数为 NaN,那么结果为 NaN。
* 如果参数为 0,那么结果为 0,符号与参数符号相同。
* 如果参数为正无穷大,那么结果为 +1.0。
* 如果参数为负无穷大,那么结果为 -1.0。
*
*/
public static double tanh(double x) {
return StrictMath.tanh(x);
}
/**
* 返回 sqrt(x^2 +y^2),没有中间溢出或下溢。
*
* 特殊情况如下:
* 如果两个参数都为无穷大,那么结果为正无穷大。
* 如果两个参数都为 NaN 且都不是无穷大,那么结果为 NaN。
*/
public static double hypot(double x, double y) {
return StrictMath.hypot(x, y);
}
/**
* 返回 e^x -1。注意,对于接近 0 的 x 值,expm1(x) + 1 比 exp(x) 更接近 e^x 的真实结果。
*
* 特殊情况如下:
* 如果参数为 NaN,那么结果为 NaN。
* 如果参数为正无穷大,那么结果为正无穷大。
* 如果参数为负无穷大,那么结果为 -1.0。
* 如果参数为 0,那么结果为 0,符号与参数符号相同。
*/
public static double expm1(double x) {
return StrictMath.expm1(x);
}
/**
* 返回ln(x+1)。注意,对于小于e的 x 值,log1p(x) 的结果比 log(1.0+x) 的浮点计算结果更接近 ln(1 + x) 的实际结果。
*
* 特殊情况如下:
* 如果参数为 NaN 或小于 -1,那么结果为 NaN。
* 如果参数为正无穷大,那么结果为正无穷大。
* 如果参数为负数,那么结果为负无穷大。
* 如果参数为 0,那么结果为 0,符号与参数符号相同。
*/
public static double log1p(double x) {
return StrictMath.log1p(x);
}
/**
* 返回第一个参数的量值和第二个参数的符号
*/
public static double copySign(double magnitude, double sign) {
return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) &
(DoubleConsts.SIGN_BIT_MASK)) |
(Double.doubleToRawLongBits(magnitude) &
(DoubleConsts.EXP_BIT_MASK |
DoubleConsts.SIGNIF_BIT_MASK)));
}
/**
* 返回第一个参数的量值和第二个参数的符号
*/
public static float copySign(float magnitude, float sign) {
return Float.intBitsToFloat((Float.floatToRawIntBits(sign) &
(FloatConsts.SIGN_BIT_MASK)) |
(Float.floatToRawIntBits(magnitude) &
(FloatConsts.EXP_BIT_MASK |
FloatConsts.SIGNIF_BIT_MASK)));
}
/**
* 返回 float 表示形式中使用的无偏指数。(即二进制中指数位的值)
* 特殊情况如下:
* 如果参数为 NaN 或无穷大,那么结果为 Float.MAX_EXPONENT + 1。
* 如果参数为 0 或 subnormal,那么结果为 Float.MIN_EXPONENT -1。
*/
public static int getExponent(float f) {
/*
* Bitwise convert f to integer, mask out exponent bits, shift
* to the right and then subtract out float's bias adjust to
* get true exponent value
*/
return ((Float.floatToRawIntBits(f) & FloatConsts.EXP_BIT_MASK) >>
(FloatConsts.SIGNIFICAND_WIDTH - 1)) - FloatConsts.EXP_BIAS;
}
/**
* 返回 double 表示形式中使用的无偏指数。(即二进制中指数位的值)
* 特殊情况如下:
* 如果参数为 NaN 或无穷大,那么结果为 Double.MAX_EXPONENT + 1。
* 如果参数为 0 或 subnormal,那么结果为 Double.MIN_EXPONENT -1。
*/
public static int getExponent(double d) {
/*
* Bitwise convert d to long, mask out exponent bits, shift
* to the right and then subtract out double's bias adjust to
* get true exponent value.
*/
return (int)(((Double.doubleToRawLongBits(d) & DoubleConsts.EXP_BIT_MASK) >>
(DoubleConsts.SIGNIFICAND_WIDTH - 1)) - DoubleConsts.EXP_BIAS);
}
/**
* 返回第一个参数和第二个参数之间与第一个参数相邻的浮点数。如果两个参数比较起来相等,则返回第二个参数。
*
* 特殊情况如下:
* 如果任一参数为 NaN,则返回 NaN。
* 如果两个参数都为有符号的 0,则不做更改地返回 direction(根据要求,如果参数比较起来相等,将返回第二个参数)。
* 如果 start 为 ±Double.MIN_VALUE,而 direction 的值要求结果为一个比 start 小的数值,那么将返回 0,并带有与 start 相同的符号。
* 如果 start 为无穷大,而 direction 的值要求结果为一个比 start 小的数值,则返回 Double.MAX_VALUE,并带有与 start 相同的符号。
* 如果 start 等于 ±Double.MAX_VALUE,而 direction 的值要求结果为一个比 start 大的数值,则返回无穷大,并带有与 start 相同的符号。
*/
public static double nextAfter(double start, double direction) {
/*
* The cases:
*
* nextAfter(+infinity, 0) == MAX_VALUE
* nextAfter(+infinity, +infinity) == +infinity
* nextAfter(-infinity, 0) == -MAX_VALUE
* nextAfter(-infinity, -infinity) == -infinity
*
* are naturally handled without any additional testing
*/
// First check for NaN values
if (Double.isNaN(start) || Double.isNaN(direction)) {
// return a NaN derived from the input NaN(s)
return start + direction;
} else if (start == direction) {
return direction;
} else { // start > direction or start < direction
// Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
// then bitwise convert start to integer.
long transducer = Double.doubleToRawLongBits(start + 0.0d);
/*
* IEEE 754 floating-point numbers are lexicographically
* ordered if treated as signed- magnitude integers .
* Since Java's integers are two's complement,
* incrementing" the two's complement representation of a
* logically negative floating-point value *decrements*
* the signed-magnitude representation. Therefore, when
* the integer representation of a floating-point values
* is less than zero, the adjustment to the representation
* is in the opposite direction than would be expected at
* first .
*/
if (direction > start) { // Calculate next greater value
transducer = transducer + (transducer >= 0L ? 1L:-1L);
} else { // Calculate next lesser value
assert direction < start;
if (transducer > 0L)
--transducer;
else
if (transducer < 0L )
++transducer;
/*
* transducer==0, the result is -MIN_VALUE
*
* The transition from zero (implicitly
* positive) to the smallest negative
* signed magnitude value must be done
* explicitly.
*/
else
transducer = DoubleConsts.SIGN_BIT_MASK | 1L;
}
return Double.longBitsToDouble(transducer);
}
}
/**
* 返回第一个参数和第二个参数之间与第一个参数相邻的浮点数。如果两个参数比较起来相等,则返回第二个参数。
*
* 特殊情况如下:
* 如果任一参数为 NaN,则返回 NaN。
* 如果两个参数都为有符号的 0,则不做更改地返回 direction(根据要求,如果参数比较起来相等,将返回第二个参数)。
* 如果 start 为 ±Float.MIN_VALUE,而 direction 的值要求结果为一个比 start 小的数值,那么将返回 0,并带有与 start 相同的符号。
* 如果 start 为无穷大,而 direction 的值要求结果为一个比 start 小的数值,则返回 Float.MAX_VALUE,并带有与 start 相同的符号。
* 如果 start 等于 ±Float.MAX_VALUE,而 direction 的值要求结果为一个比 start 大的数值,则返回无穷大,并带有与 start 相同的符号。
*/
public static float nextAfter(float start, double direction) {
/*
* The cases:
*
* nextAfter(+infinity, 0) == MAX_VALUE
* nextAfter(+infinity, +infinity) == +infinity
* nextAfter(-infinity, 0) == -MAX_VALUE
* nextAfter(-infinity, -infinity) == -infinity
*
* are naturally handled without any additional testing
*/
// First check for NaN values
if (Float.isNaN(start) || Double.isNaN(direction)) {
// return a NaN derived from the input NaN(s)
return start + (float)direction;
} else if (start == direction) {
return (float)direction;
} else { // start > direction or start < direction
// Add +0.0 to get rid of a -0.0 (+0.0 + -0.0 => +0.0)
// then bitwise convert start to integer.
int transducer = Float.floatToRawIntBits(start + 0.0f);
/*
* IEEE 754 floating-point numbers are lexicographically
* ordered if treated as signed- magnitude integers .
* Since Java's integers are two's complement,
* incrementing" the two's complement representation of a
* logically negative floating-point value *decrements*
* the signed-magnitude representation. Therefore, when
* the integer representation of a floating-point values
* is less than zero, the adjustment to the representation
* is in the opposite direction than would be expected at
* first.
*/
if (direction > start) {// Calculate next greater value
transducer = transducer + (transducer >= 0 ? 1:-1);
} else { // Calculate next lesser value
assert direction < start;
if (transducer > 0)
--transducer;
else
if (transducer < 0 )
++transducer;
/*
* transducer==0, the result is -MIN_VALUE
*
* The transition from zero (implicitly
* positive) to the smallest negative
* signed magnitude value must be done
* explicitly.
*/
else
transducer = FloatConsts.SIGN_BIT_MASK | 1;
}
return Float.intBitsToFloat(transducer);
}
}
/**
* 返回 d 和正无穷大之间与 d 相邻的浮点值。此方法在语义上等同于 nextAfter(d, Double.POSITIVE_INFINITY);
* 但是,nextUp 实现的返回速度可能比其等价 nextAfter 调用快。
*
* 特殊情况如下:
* 如果参数为 NaN,那么结果为 NaN。
* 如果参数为正无穷大,那么结果为正无穷大。
* 如果参数为 0,那么结果为 Double.MIN_VALUE。
*
*/
public static double nextUp(double d) {
if( Double.isNaN(d) || d == Double.POSITIVE_INFINITY)
return d;
else {
d += 0.0d;
return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
((d >= 0.0d)?+1L:-1L));
}
}
/**
* 返回 f 和正无穷大之间与 f 相邻的浮点值。此方法在语义上等同于 nextAfter(d, Float.POSITIVE_INFINITY);
* 但是,nextUp 实现的返回速度可能比其等价 nextAfter 调用快。
*
* 特殊情况如下:
* 如果参数为 NaN,那么结果为 NaN。
* 如果参数为正无穷大,那么结果为正无穷大。
* 如果参数为 0,那么结果为 Float.MIN_VALUE。
*/
public static float nextUp(float f) {
if( Float.isNaN(f) || f == FloatConsts.POSITIVE_INFINITY)
return f;
else {
f += 0.0f;
return Float.intBitsToFloat(Float.floatToRawIntBits(f) +
((f >= 0.0f)?+1:-1));
}
}
/**
* 返回 d 和负无穷大之间与 d 相邻的浮点值。 这种方法在语义上相当于nextAfter(d, Double.NEGATIVE_INFINITY)
*
* 特殊情况:
* 如果参数是NaN,结果是NaN。
* 如果参数为负无穷大,则结果为负无穷大。
* 如果参数为零,结果为-Double.MIN_VALUE
*/
public static double nextDown(double d) {
if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY)
return d;
else {
if (d == 0.0)
return -Double.MIN_VALUE;
else
return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
((d > 0.0d)?-1L:+1L));
}
}
/**
* 返回 f 和负无穷大之间与 f 相邻的浮点值。 这种方法在语义上相当于nextAfter(d, Float.NEGATIVE_INFINITY)
*
* 特殊情况:
* 如果参数是NaN,结果是NaN。
* 如果参数为负无穷大,则结果为负无穷大。
* 如果参数为零,结果为-Float.MIN_VALUE
*/
public static float nextDown(float f) {
if (Float.isNaN(f) || f == Float.NEGATIVE_INFINITY)
return f;
else {
if (f == 0.0f)
return -Float.MIN_VALUE;
else
return Float.intBitsToFloat(Float.floatToRawIntBits(f) +
((f > 0.0f)?-1:+1));
}
}
/**
* 返回 d × 2^(scaleFactor)
*/
public static double scalb(double d, int scaleFactor) {
/*
* This method does not need to be declared strictfp to
* compute the same correct result on all platforms. When
* scaling up, it does not matter what order the
* multiply-store operations are done; the result will be
* finite or overflow regardless of the operation ordering.
* However, to get the correct result when scaling down, a
* particular ordering must be used.
*
* When scaling down, the multiply-store operations are
* sequenced so that it is not possible for two consecutive
* multiply-stores to return subnormal results. If one
* multiply-store result is subnormal, the next multiply will
* round it away to zero. This is done by first multiplying
* by 2 ^ (scaleFactor % n) and then multiplying several
* times by by 2^n as needed where n is the exponent of number
* that is a covenient power of two. In this way, at most one
* real rounding error occurs. If the double value set is
* being used exclusively, the rounding will occur on a
* multiply. If the double-extended-exponent value set is
* being used, the products will (perhaps) be exact but the
* stores to d are guaranteed to round to the double value
* set.
*
* It is _not_ a valid implementation to first multiply d by
* 2^MIN_EXPONENT and then by 2 ^ (scaleFactor %
* MIN_EXPONENT) since even in a strictfp program double
* rounding on underflow could occur; e.g. if the scaleFactor
* argument was (MIN_EXPONENT - n) and the exponent of d was a
* little less than -(MIN_EXPONENT - n), meaning the final
* result would be subnormal.
*
* Since exact reproducibility of this method can be achieved
* without any undue performance burden, there is no
* compelling reason to allow double rounding on underflow in
* scalb.
*/
// magnitude of a power of two so large that scaling a finite
// nonzero value by it would be guaranteed to over or
// underflow; due to rounding, scaling down takes takes an
// additional power of two which is reflected here
final int MAX_SCALE = DoubleConsts.MAX_EXPONENT + -DoubleConsts.MIN_EXPONENT +
DoubleConsts.SIGNIFICAND_WIDTH + 1;
int exp_adjust = 0;
int scale_increment = 0;
double exp_delta = Double.NaN;
// Make sure scaling factor is in a reasonable range
if(scaleFactor < 0) {
scaleFactor = Math.max(scaleFactor, -MAX_SCALE);
scale_increment = -512;
exp_delta = twoToTheDoubleScaleDown;
}
else {
scaleFactor = Math.min(scaleFactor, MAX_SCALE);
scale_increment = 512;
exp_delta = twoToTheDoubleScaleUp;
}
// Calculate (scaleFactor % +/-512), 512 = 2^9, using
// technique from "Hacker's Delight" section 10-2.
int t = (scaleFactor >> 9-1) >>> 32 - 9;
exp_adjust = ((scaleFactor + t) & (512 -1)) - t;
d *= powerOfTwoD(exp_adjust);
scaleFactor -= exp_adjust;
while(scaleFactor != 0) {
d *= exp_delta;
scaleFactor -= scale_increment;
}
return d;
}
/**
* 返回 f × 2^(scaleFactor)
*/
public static float scalb(float f, int scaleFactor) {
// magnitude of a power of two so large that scaling a finite
// nonzero value by it would be guaranteed to over or
// underflow; due to rounding, scaling down takes takes an
// additional power of two which is reflected here
final int MAX_SCALE = FloatConsts.MAX_EXPONENT + -FloatConsts.MIN_EXPONENT +
FloatConsts.SIGNIFICAND_WIDTH + 1;
// Make sure scaling factor is in a reasonable range
scaleFactor = Math.max(Math.min(scaleFactor, MAX_SCALE), -MAX_SCALE);
/*
* Since + MAX_SCALE for float fits well within the double
* exponent range and + float -> double conversion is exact
* the multiplication below will be exact. Therefore, the
* rounding that occurs when the double product is cast to
* float will be the correctly rounded float result. Since
* all operations other than the final multiply will be exact,
* it is not necessary to declare this method strictfp.
*/
return (float)((double)f*powerOfTwoD(scaleFactor));
}
// Constants used in scalb
static double twoToTheDoubleScaleUp = powerOfTwoD(512);
static double twoToTheDoubleScaleDown = powerOfTwoD(-512);
/**
* Returns a floating-point power of two in the normal range.
*/
static double powerOfTwoD(int n) {
assert(n >= DoubleConsts.MIN_EXPONENT && n <= DoubleConsts.MAX_EXPONENT);
return Double.longBitsToDouble((((long)n + (long)DoubleConsts.EXP_BIAS) <<
(DoubleConsts.SIGNIFICAND_WIDTH-1))
& DoubleConsts.EXP_BIT_MASK);
}
/**
* Returns a floating-point power of two in the normal range.
*/
static float powerOfTwoF(int n) {
assert(n >= FloatConsts.MIN_EXPONENT && n <= FloatConsts.MAX_EXPONENT);
return Float.intBitsToFloat(((n + FloatConsts.EXP_BIAS) <<
(FloatConsts.SIGNIFICAND_WIDTH-1))
& FloatConsts.EXP_BIT_MASK);
}
}