---- digital bit computing to hexadecimal

Given an integer, write an algorithm to convert this number to a hexadecimal number. For negative integer, we usually use complement arithmetic method.

note:

HEX All letters (af) must be lowercase.
Hex string can not contain excess leading zeros. If the number to be transformed is 0, then a single character '0' is represented; other cases, the hexadecimal character string will not be the first character 0. 
To ensure that a given number in the range of 32-bit signed integer.
Not use any digital library provided by a method of direct conversion or hexadecimal format.
Example 1:

Input:
26

Output:
". 1A"
Example 2:

Input:
-1

Output:
"ffffffff"

 

 

[Notes] The core idea of ​​using a bit operation, each 4 bits, corresponding to a hexadecimal number.

  • Use 0xf(00 ... 01111b) to obtain numa low of four.
  • >>Arithmetic displacement, wherein a positive number of 0 up right left, right left S.1 negative.
  • Displacement calculation does not guarantee num==0, required to ensure that 32-bit int (corresponding to hexadecimal 8 or less).

Use string directly string concatenation ....

string toHex(int num) {
    if (num == 0) return "0"; string hex = "0123456789abcdef", ans = ""; while(num && ans.size() < 8){ ans = hex[num & 0xf] + ans; num >>= 4; } return ans; }

Guess you like

Origin www.cnblogs.com/pacino12134/p/11057855.html