android 里 ,如何将 int 转换为char 的16进制,将string 类型的转byte[] 的算法
1. int 转换为char 的16进制
比如,int i = 10 ,想得到 char w = 0x0A;
比如int i = 1, 想得到 char w = 0x01;
2 将string 类型的转byte[]
byte [] buff = new byte[30];
比如 String str= "1"
想得到 buff[0] = 0x01;
比如 str = "10"
想得到 buff[0] = 0x0A;
比如 str = "1011"
buff[0]= 0x0A;
想得到 buff[1] = 0x0B;
public String getHexString() {
//char to hex.
// char character = 'a';
// String str = String.valueOf(character);
//String to hex.
String str = "aA";
StringBuilder sb = new StringBuilder();
char[] charArray = str.toCharArray();
if (charArray != null) {
for (char c : charArray) {
byte byteHigh = (byte)(c >> 8 & 0xff);
byte byteLow = (byte)(c & 0xff);
sb.append(convertByteToHex(byteHigh));
sb.append(convertByteToHex(byteLow));
}
}
return sb.toString();
}
private String convertByteToHex(byte b) {
int high = b / 16;
int low = b % 16;
return getHex(high) + getHex(low);
}
private String getHex(int nibble) {
switch (nibble) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return String.valueOf(nibble);
case 10:
return "A";
case 11:
return "B";
case 12:
return "C";
case 13:
return "D";
case 14:
return "E";
case 15:
return "F";
}
return "";
}