public class Convertor {
private static final char[] c = {'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'};
public static String toBinaryString(int i){
return toUnsignedString(i, 1);
}
public static String toHexString(int i){
return toUnsignedString(i, 4);
}
private static String toUnsignedString(int i, int shift){
char[] s = new char[32];
int mask = (1<<shift) - 1;
int p = 31;
while(i != 0){
s[p] = c[i & mask];
i = i >>> shift;
p--;
}
return new String(s, p+1, 31-p);
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(Convertor.toBinaryString(-16));
System.out.println(Convertor.toHexString(16));
System.out.println(Integer.toString(16));
}
}
进制转换
最新推荐文章于 2024-07-24 10:44:50 发布