1# SPDX-License-Identifier: Apache-2.0
2
3# from https://gist.github.com/korzo89/71a6de0f388f7cf8b349101b0134060c
4function(from_hex HEX DEC)
5    string(SUBSTRING "${HEX}" 2 -1 HEX)
6    string(TOUPPER "${HEX}" HEX)
7    set(_res 0)
8    string(LENGTH "${HEX}" _strlen)
9
10    while(_strlen GREATER 0)
11        math(EXPR _res "${_res} * 16")
12        string(SUBSTRING "${HEX}" 0 1 NIBBLE)
13        string(SUBSTRING "${HEX}" 1 -1 HEX)
14        if(NIBBLE STREQUAL "A")
15            math(EXPR _res "${_res} + 10")
16        elseif(NIBBLE STREQUAL "B")
17            math(EXPR _res "${_res} + 11")
18        elseif(NIBBLE STREQUAL "C")
19            math(EXPR _res "${_res} + 12")
20        elseif(NIBBLE STREQUAL "D")
21            math(EXPR _res "${_res} + 13")
22        elseif(NIBBLE STREQUAL "E")
23            math(EXPR _res "${_res} + 14")
24        elseif(NIBBLE STREQUAL "F")
25            math(EXPR _res "${_res} + 15")
26        else()
27            math(EXPR _res "${_res} + ${NIBBLE}")
28        endif()
29
30        string(LENGTH "${HEX}" _strlen)
31    endwhile()
32
33    set(${DEC} ${_res} PARENT_SCOPE)
34endfunction()
35
36function(to_hex DEC HEX)
37    while(DEC GREATER 0)
38        math(EXPR _val "${DEC} % 16")
39        math(EXPR DEC "${DEC} / 16")
40        if(_val EQUAL 10)
41            set(_val "A")
42        elseif(_val EQUAL 11)
43            set(_val "B")
44        elseif(_val EQUAL 12)
45            set(_val "C")
46        elseif(_val EQUAL 13)
47            set(_val "D")
48        elseif(_val EQUAL 14)
49            set(_val "E")
50        elseif(_val EQUAL 15)
51            set(_val "F")
52        endif()
53        set(_res "${_val}${_res}")
54    endwhile()
55    set(${HEX} "0x${_res}" PARENT_SCOPE)
56endfunction()
57