-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathconvert_a_number_to_hexadecimal.go
130 lines (102 loc) · 2.09 KB
/
convert_a_number_to_hexadecimal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main
// Real Solution
//----------------------------------------
// func toHex(num int) string {
// if num == 0 {
// return "0"
// }
// const bitsPerDigit = 4
// const mask = (1 << bitsPerDigit) - 1
// hex := make([]byte, 8)
// i := 7
// // Convert negative numbers to their two's complement representation
// if num < 0 {
// num = (1 << 32) + num
// }
// for num != 0 {
// nib := num & mask
// hex[i] = getHexDigit(nib)
// num >>= bitsPerDigit
// i--
// }
// return string(hex[i+1:])
// }
// func getHexDigit(n int) byte {
// if n < 10 {
// return byte('0' + n)
// }
// return byte('a' + n - 10)
// }
//--------------------------
// Just for Fun
import (
"fmt"
"math"
)
func ToHex(n interface{}) (string, error) {
switch v := n.(type) {
case int:
return toHexInt(int32(v)), nil
case int32:
return toHexInt(v), nil
case int64:
return toHexInt64(v), nil
case float32:
return toHexFloat(float64(v)), nil
case float64:
return toHexFloat(v), nil
default:
return "", fmt.Errorf("Unsupported type: %T", v)
}
}
func toHexInt(n int32) string {
if n == 0 {
return "0"
}
ref := "0123456789abcdef"
result := ""
for n != 0 {
result = string(ref[n&0xF]) + result
n >>= 4
}
return result
}
func toHexInt64(n int64) string {
if n == 0 {
return "0"
}
ref := "0123456789abcdef"
result := ""
for n != 0 {
result = string(ref[n&0xF]) + result
n >>= 4
}
return result
}
func toHexFloat(n float64) string {
bits := math.Float64bits(n)
ref := "0123456789abcdef"
result := ""
for i := 60; i >= 0; i -= 4 {
nibble := (bits >> i) & 0xF
result += string(ref[nibble])
}
return result
}
func main() {
num := 255
hexStr, _ := ToHex(num)
fmt.Println(hexStr) // Output: ff
num32 := int32(65535)
hexStr32, _ := ToHex(num32)
fmt.Println(hexStr32) // Output: ffff
num64 := int64(4294967295)
hexStr64, _ := ToHex(num64)
fmt.Println(hexStr64) // Output: ffffffff
f := float32(3.14)
hexFloat, _ := ToHex(f)
fmt.Println(hexFloat) // Output: 4048f5c3
d := 3.14159
hexDouble, _ := ToHex(d)
fmt.Println(hexDouble) // Output: 400921fb54442d18
}