import static java.lang.System.out; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class NativeMethod { public native int T(String str); public String toBinaryString(int i) { return toUnsignedString(i, 1); } public String toOctalString(int i) { return toUnsignedString(i, 3); } public String toHexString(int i) { return toUnsignedString(i, 4); } private String toUnsignedString(int i, int shift) { char[] str = new char[32]; int charPos = 32; int mask = 1 << shift; --mask; do { str[--charPos] = digits[i & mask]; i >>>= shift; } while (i != 0); return new String(str, charPos, 32 - charPos); } public static String toBinaryString(byte b) { char[] str = new char[32]; int charPos = 32; int mask = 1 << 4; /* * Very Important: *1)位运算符只针对4byte的int型 *2)-2的byte类型 16进制表示为FE(2取反加1) *3)-2 & 0xFF运算: 实际-2带符号位bit-wise成 * int,即FE会变成FFFFFFFE(2取反加1), * 接着 0xFFFFFFFE & 0x000000FF = 0x 000000FE; * 如果不&,就是FFFFFFFE。 */ int i = b & 0xff; --mask; do { str[--charPos] = digits[i & mask]; i >>>= 4; } while (i != 0); return new String(str, charPos, 32 - charPos); } 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' }; }