Ideas:
- Take out the last four digits of the int number each time and convert them to the corresponding hexadecimal number;
- Perform a logical shift to the right by 4 bits -> it means to shift out the four that has just been taken out
- Repeat the above operation until the value of int is all 0
Supplement:
This is a logical shift, because the logical shift is zero-filled regardless of whether it is a complement or the original code. It is convenient to observe whether all the values are 0, you can end.
Code:
public String toHex(int num) {
if (num == 0) return "0";
char[] ant = "0123456789abcdef".toCharArray();
StringBuilder sb = new StringBuilder();
while (num != 0 && sb.length() < 8) {
sb.append(ant[num & 0xf]);//num & 0xf 表示int中低四位的二进制数表示的大小
num >>>= 4;
}
return sb.reverse().toString(); //此处需要将StringBuilder里面的字符串反转,因为添加时是从低位开始添加的
}