1# SPDX-License-Identifier: Apache-2.0
2
3# This code was deprecated after Zephyr v3.5.0
4message(DEPRECATION "The to_hex() and from_hex() functions are deprecated. Please "
5                    "use CMake's math(... OUTPUT_FORMAT <format>) instead.")
6
7# from https://gist.github.com/korzo89/71a6de0f388f7cf8b349101b0134060c
8function(from_hex HEX DEC)
9    string(SUBSTRING "${HEX}" 2 -1 HEX)
10    string(TOUPPER "${HEX}" HEX)
11    set(_res 0)
12    string(LENGTH "${HEX}" _strlen)
13
14    while(_strlen GREATER 0)
15        math(EXPR _res "${_res} * 16")
16        string(SUBSTRING "${HEX}" 0 1 NIBBLE)
17        string(SUBSTRING "${HEX}" 1 -1 HEX)
18        if(NIBBLE STREQUAL "A")
19            math(EXPR _res "${_res} + 10")
20        elseif(NIBBLE STREQUAL "B")
21            math(EXPR _res "${_res} + 11")
22        elseif(NIBBLE STREQUAL "C")
23            math(EXPR _res "${_res} + 12")
24        elseif(NIBBLE STREQUAL "D")
25            math(EXPR _res "${_res} + 13")
26        elseif(NIBBLE STREQUAL "E")
27            math(EXPR _res "${_res} + 14")
28        elseif(NIBBLE STREQUAL "F")
29            math(EXPR _res "${_res} + 15")
30        else()
31            math(EXPR _res "${_res} + ${NIBBLE}")
32        endif()
33
34        string(LENGTH "${HEX}" _strlen)
35    endwhile()
36
37    set(${DEC} ${_res} PARENT_SCOPE)
38endfunction()
39
40function(to_hex DEC HEX)
41    if(DEC EQUAL 0)
42        set(${HEX} "0x0" PARENT_SCOPE)
43        return()
44    endif()
45    while(DEC GREATER 0)
46        math(EXPR _val "${DEC} % 16")
47        math(EXPR DEC "${DEC} / 16")
48        if(_val EQUAL 10)
49            set(_val "A")
50        elseif(_val EQUAL 11)
51            set(_val "B")
52        elseif(_val EQUAL 12)
53            set(_val "C")
54        elseif(_val EQUAL 13)
55            set(_val "D")
56        elseif(_val EQUAL 14)
57            set(_val "E")
58        elseif(_val EQUAL 15)
59            set(_val "F")
60        endif()
61        set(_res "${_val}${_res}")
62    endwhile()
63    set(${HEX} "0x${_res}" PARENT_SCOPE)
64endfunction()
65