| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
local bit = require 'bit' |
| 20 |
|
| 21 |
do |
| 22 |
|
| 23 |
local function to_hex(n) |
| 24 |
if(type(n) ~= "number") then |
| 25 |
error("non-number type passed in.") |
| 26 |
end |
| 27 |
|
| 28 |
|
| 29 |
if(n - math.floor(n) > 0) then |
| 30 |
error("trying to apply bitwise operation on non-integer!") |
| 31 |
end |
| 32 |
|
| 33 |
if(n < 0) then |
| 34 |
|
| 35 |
n = bit.tobits(bit.bnot(math.abs(n)) + 1) |
| 36 |
n = bit.tonumb(n) |
| 37 |
end |
| 38 |
|
| 39 |
local hex_tbl = {'A', 'B', 'C', 'D', 'E', 'F'} |
| 40 |
local hex_str = "" |
| 41 |
|
| 42 |
while(n ~= 0) do |
| 43 |
local last = math.mod(n, 16) |
| 44 |
if(last < 10) then |
| 45 |
hex_str = tostring(last) .. hex_str |
| 46 |
else |
| 47 |
hex_str = hex_tbl[last-10+1] .. hex_str |
| 48 |
end |
| 49 |
n = math.floor(n/16) |
| 50 |
end |
| 51 |
if(hex_str == "") then |
| 52 |
hex_str = "0" |
| 53 |
end |
| 54 |
return "0x" .. hex_str |
| 55 |
end |
| 56 |
|
| 57 |
local function to_dec(hex) |
| 58 |
if(type(hex) ~= "string") then |
| 59 |
error("non-string type passed in.") |
| 60 |
end |
| 61 |
|
| 62 |
local head = string.sub(hex, 1, 2) |
| 63 |
|
| 64 |
if( head ~= "0x" and head ~= "0X") then |
| 65 |
error("wrong hex format, should lead by 0x or 0X.") |
| 66 |
end |
| 67 |
|
| 68 |
return tonumber(string.sub(hex, 3), 16) |
| 69 |
end |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
local hex = { |
| 74 |
to_dec = to_dec, |
| 75 |
to_hex = to_hex, |
| 76 |
} |
| 77 |
|
| 78 |
return hex |
| 79 |
|
| 80 |
end |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|