Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
- All letters in hexadecimal (
a-f
) must be in lowercase. - The hexadecimal string must not contain extra leading
0
s. If the number is zero, it is represented by a single zero character'0'
; otherwise, the first character in the hexadecimal string will not be the zero character. - The given number is guaranteed to fit within the range of a 32-bit signed integer.
- You must not use any method provided by the library which converts/formats the number to hex direct.
Answer:
public class toHex { public static void main(String[] args) { int num = -5; char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; /*定义一张图 分别放入16个代表十六进制中的数*/ System.out.println(toHexMethod(num,map)); } private static String toHexMethod(int num,char[] map) { if(num == 0) return "0"; String result = ""; while(num != 0){ result = map[(num & 15)] + result; num = (num >>> 4); } return result; } }
主要利用计算机二进制计算原理;
<< : 左移运算符,num << 1,相当于num乘以2
>> : 右移运算符,num >> 1,相当于num除以2
>>> : 无符号右移,忽略符号位,空位都以0补齐
<< : 左移运算符,num << 1,相当于num乘以2
>> : 右移运算符,num >> 1,相当于num除以2
>>> : 无符号右移,忽略符号位,空位都以0补齐