Byte类源码解析

 

Byte是java.lang包的一个类,是基本类型byte的包装类.Byte默认为2个字节, 最大值为32767,最小值为-32768

 

public static Byte decode (String  nm) throws NumberFormatException 方法

String 解码为 Byte 。接受按下列语法给出的十进制、十六进制和八进制数:
DecodableString:
Signopt DecimalNumeral
Signopt 0x HexDigits
Signopt 0X HexDigits
Signopt # HexDigits
Signopt 0 OctalDigits
Sign:
-
Java Language Specification§3.10.1 中给出了 DecimalNumeralHexDigitsOctalDigits 的定义。

对(可选)负号和/或基数说明符(“0x ”、“0X ”、“# ” 或前导零)后面的字符序列进行解析就如同使用带指定基数(10、16 或 8)的 Byte.parseByte 方法一样。该字符序列必须表示一个正值,否则将抛出 NumberFormatException 。如果指定 String 的第一个字符是负号,则结果将被求反。该 String 中不允许出现空白字符。

 

/**
	 * 将String解码成Byte
	 * @param nm 16进制/8进制/10进制的正数/负数
	 * @return
	 */
	public static myjava.lang.Byte decode(String nm) {
		//默认为正数
		boolean negative = false;
		//默认为10进制
		int radix = 10;
		int index = 0;
		
		if (nm.startsWith("-")) {
			index++;
		}
		
		//16进制数
		if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
			radix = 16;
			index += 2;
		} 
		//
		else if (nm.startsWith("#", index)) {
			radix = 16;
			index++;
		} 
		//8进制数
		else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
			radix = 8;
			index++;
		}
		myjava.lang.Byte result;
		try {
			//用valueOf第二参数所给定的基数指定对字符串解析时提取的
			result = valueOf(nm.substring(index), radix);
			result = negative ? new myjava.lang.Byte((byte) -result.byteValue()) : result;
		} catch (NumberFormatException e) {
			String constant = negative ? new String("-" + nm.substring(index)) : nm.substring(index);
			result = valueOf(constant, radix);
		}
		return result;
	}
 

 

你可能感兴趣的:(byte)