package LeeCode;
/**
* @ClassName ToHex
* @Description 给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。
* 注意:
* 十六进制中所有字母(a-f)都必须是小写。
* 十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。
* 给定的数确保在32位有符号整数范围内。
* 不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。
* @Author Kingsley
* @Date 2020/3/12 15:57
* @Version 1.0
**/
public class ToHex {
//正数可以,负数就不行了
public static String toHex(int num) {
if(num == 0)
return "0";
char[] c = {'0','1', '2','3','4', '5', '6', '7','8','9','a','b','c','d','e','f'};
StringBuilder sb = new StringBuilder();
while (num != 0){
sb.insert(0, c[num % 16]);
num /= 16;
}
return sb.toString();
}
//正负数都要可以的算法,0xf 0x代表这是16进制的数,f代表15,所以0xf就是15
public static String toHexDemo(int num) {
if(num == 0)
return "0";
char[] c = {'0','1','2','3','4', '5', '6', '7','8','9','a','b','c','d','e','f'};
StringBuilder sb = new StringBuilder();
int tmp = 0;
while (num != 0){
//num和0xf做与运算就是把num的二进制形式的后四位取出来,表示成16进制中的数。
//可举例 100的二进制: 1100100 0xf的二进制 : 0001111 与运算的结果就是0000100
tmp = (num & 0xf);
sb.insert(0, c[tmp]);
//取了四位之后,就将num右移四位
//按位右移补零操作符。左操作数的值按右操作数指定的位数右移,移动得到的空位以零填充。
//无符号右移,不论正负,高位均补0
num >>>=4;
//>> 有符号右移,原数是正数 高位补0;是负数,高位补1 有符号数高位0代表正数,高位1代表负数
}
return sb.toString();
}
public static void main(String[] args) {
int num = -10;
String res = toHexDemo(num);
System.out.println(res);
}
}
That explains the code, recording operations, and some of the bit-complement, the concept of the number of symbols
1. The complement is a positive number of its own
2's complement negative numbers are two's complement positive number + 1; and the highest bit is 1
. 3 >>> unsigned right shift operator, 0s are high.
Complement:
- Positive
integer which is the complement binary representation, the same as the original code [3].
Example: +9 complement is 00001001. (Note: this is +9 complement 8-bit binary represented, many complement representation, as well as 16-bit twos complement representation, and a 32-bit twos complement representation of the 64-bit twos complement code representation and the like. each two's complement representation can only be represented by a limited number.) - Negative
seeking complement negative integers, which in addition to the original code symbol after bit inversion of all bits (1, 1 becomes 0 becomes 0, the sign bit is a constant) plus 1 [4].
The same numbers in different complement representation is different. Such as -15 complement, it is in 8-bit binary 11110001, but in 16-bit two's complement binary representation is 1111111111110001. The following are 8-bit binary to represent.
Example: twos complement -5.
-5 corresponds to a positive number 5 (00000101) → all the bits (11111010) → plus 1 (11111011)
so -5 complement is 11111011. - 0 complement the
number of 0's complement representation is only [3].
[+0] Complement = [0 +] trans = [+ 0] = 00000000 original
[-0] Complement 00000000 = 11111111 + 1 =