2010-04-14 68 views
0

在JDK或Apache Commons(或其他jar)中是否有這樣的東西?字節toPositiveInt方法

/** 
* Return the integer positive value of the byte. (e.g. -128 will return 
* 128; -127 will return 129; -126 will return 130...) 
*/ 
public static int toPositiveInt(byte b) { 
int intV = b; 
if (intV < 0) { 
    intV = -intV; 
    int diff = ((Byte.MAX_VALUE + 1) - intV) + 1; 
    intV = Byte.MAX_VALUE + diff; 
} 
return intV; 
    } 

回答

3

通常情況下,你使用一些基本的位操作此:

public static int toPositiveInt(byte b) { 
return b & 0xFF; 
} 

而且因爲它是如此之短,它通常是內聯,而不是被稱爲方法。

+0

很酷........ XD – 2010-04-14 20:57:49

+0

我完全忘記了位操作存在 – 2010-04-14 21:02:01