今天看公司大神写的java代码,数组下标用十六进制表示。当然代码得修改才能用。其中用法的优缺点以及适用的场景。
第一部分
class Inter{
static final 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'
};
static final char[] UPPER_CASE_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'
};
public static void printUppercaseByteArraWithHexIndex(byte[] bytes){
char[] digits = UPPER_CASE_DIGITS;
for (byte b : bytes){
System.out.println(digits[(b >> 4) & 0xf]);
System.out.println(digits[b & 0xf]);
}
}
public static String bytesToHexString(byte [] bytes, boolean upperCase) {
char[] digits = upperCase ? UPPER_CASE_DIGITS : DIGITS;
char[] buf = new char[bytes.length * 2];
int c = 0;
for (byte b : bytes) {
buf[c++] = digits[(b >> 4) & 0xf];
buf[c++] = digits[b & 0xf];
}
return new String(buf);
}
}
第二部分(主函数)
public static void main(String args[]){
byte[] bytesa = {(byte) 0x5A, (byte) 0xa6, (byte) 0x1a, (byte) 0x3a, (byte) 0xaa};
String s = Inter.bytesToHexString(bytesa,true );
System.out.println(s);
Inter.printUppercaseByteArraWithHexIndex(bytesa);
}