public class Test {
final static char[] digitals = {
'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'
};
/**
* Convert the integer to an unsigned number.
*
* @param i
* @param shift
* @return
*/
private static String toUnsignedString(int i, int shift) {
char[] buf = new char[32];
int charPos = 32;
int radix = 1 << shift;
int mask = radix - 1;
do {
buf[--charPos] = digitals[i & mask];
i = i >>> shift;
} while(i != 0);
return new String(buf, charPos, (32 - charPos));
}
public static void main(String[] args) {
System.out.println(Test.toUnsignedString(1024, 4));
}
}
Integer的toHexString实现方法,恩,写的很好,学习学习。
下面是将byte数组转换为HexString的方法。
需要注意的:buf[2*i] = digitals.values()[(b[i] & 0xff) >>> shift].getC();
要&0xff,因为如果对char、byte或者short类型的数值进行移位处理,那么在移位进行之前,它们会被转换为int类型,并且得到的结果也是一个int类型的值。
如果byte数值超过2^7,即128,转换为int时就会在前面加1。
要加(),因为>>>操作符的优先级高于&。
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Util {
enum digitals {
ZERO('0'), ONE('1'), TWO('2'), THREE('3'), FOUR('4'), FIVE('5'),
SIX('6'), SEVEN('7'), EIGHT('8'), NINE('9'), A('A'), B('B'),
C('C'), D('D'), E('E'), F('F'), G('G'), H('H'),
I('I'), J('J'), K('K'), L('L'), M('M'), N('N'),
O('O'), P('P'), Q('Q'), R('R'), S('S'), T('T'),
U('U'), V('V'), W('W'), X('X'), Y('Y'), Z('Z');
private char c;
public char getC() {
return c;
}
public void setC(char c) {
this.c = c;
}
private digitals(char c) {
this.c = c;
}
}
/**
* Convert the byte array to string
* @param b
* @param shift
* @return
*/
public static String byteArrayToString(byte[] b, int shift) {
int len = b.length;
char[] buf = new char[2 * len];
int radix = 1 << shift;
int mask = radix - 1;
for(int i = 0; i < len; i++) {
buf[2*i] = digitals.values()[(b[i] & 0xff) >>> shift].getC();
buf[2*i + 1] = digitals.values()[b[i] & mask].getC();
}
return new String(buf);
}
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("d://t");
byte[] b= new byte[16];
is.read(b);
System.out.println(Util.byteArrayToString(b, 4));
}
}
参考:java操作符优先级