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