Y: 是否可以采用带有16位十进制的变量A并将其转换为10十六进制,反之亦然,在CMake中?
谷歌搜索只引出了以下内容:
http://public.kitware.com/pipermail/cmake/2008-September/024092.html
不进行转换。
X: 我正在尝试使用“配置文件”,将配置的值作为小数读取,并在配置的头文件中将其作为十六进制输出。
答案 0 :(得分:2)
我自己动手,但感觉应该是内置的
cmake_minimum_required (VERSION 2.6.4)
macro(HEXCHAR2DEC VAR VAL)
if (${VAL} MATCHES "[0-9]")
SET(${VAR} ${VAL})
elseif(${VAL} MATCHES "[aA]")
SET(${VAR} 10)
elseif(${VAL} MATCHES "[bB]")
SET(${VAR} 11)
elseif(${VAL} MATCHES "[cC]")
SET(${VAR} 12)
elseif(${VAL} MATCHES "[dD]")
SET(${VAR} 13)
elseif(${VAL} MATCHES "[eE]")
SET(${VAR} 14)
elseif(${VAL} MATCHES "[fF]")
SET(${VAR} 15)
else()
MESSAGE(FATAL_ERROR "Invalid format for hexidecimal character")
endif()
endmacro(HEXCHAR2DEC)
macro(HEX2DEC VAR VAL)
IF (${VAL} EQUAL 0)
SET(${VAR} 0)
ELSE()
SET(CURINDEX 0)
STRING(LENGTH "${VAL}" CURLENGTH)
SET(${VAR} 0)
while (CURINDEX LESS CURLENGTH)
STRING(SUBSTRING "${VAL}" ${CURINDEX} 1 CHAR)
HEXCHAR2DEC(CHAR ${CHAR})
MATH(EXPR POWAH "(1<<((${CURLENGTH}-${CURINDEX}-1)*4))")
MATH(EXPR CHAR "(${CHAR}*${POWAH})")
MATH(EXPR ${VAR} "${${VAR}}+${CHAR}")
MATH(EXPR CURINDEX "${CURINDEX}+1")
endwhile()
ENDIF()
endmacro(HEX2DEC)
macro(DECCHAR2HEX VAR VAL)
if (${VAL} LESS 10)
SET(${VAR} ${VAL})
elseif(${VAL} EQUAL 10)
SET(${VAR} "A")
elseif(${VAL} EQUAL 11)
SET(${VAR} "B")
elseif(${VAL} EQUAL 12)
SET(${VAR} "C")
elseif(${VAL} EQUAL 13)
SET(${VAR} "D")
elseif(${VAL} EQUAL 14)
SET(${VAR} "E")
elseif(${VAL} EQUAL 15)
SET(${VAR} "F")
else()
MESSAGE(FATAL_ERROR "Invalid format for hexidecimal character")
endif()
endmacro(DECCHAR2HEX)
macro(DEC2HEX VAR VAL)
if (${VAL} EQUAL 0)
SET(${VAR} 0)
ELSE()
SET(VAL2 ${VAL})
SET(${VAR} "")
WHILE (${VAL2} GREATER 0)
MATH(EXPR VALCHAR "(${VAL2}&15)")
DECCHAR2HEX(VALCHAR ${VALCHAR})
SET(${VAR} "${VALCHAR}${${VAR}}")
MATH(EXPR VAL2 "${VAL2} >> 4")
ENDWHILE()
ENDIF()
endmacro(DEC2HEX)
答案 1 :(得分:1)
使用一些技巧,你可以相当简单地做到这一点。 CMake的表达式在内部使用int
,因此它最多只能工作2个 31 -1位。像这样的东西(你可能想要改变大端或其他什么)。
function (NumberToHex number output)
set (chars "0123456789abcdef")
set (hex "")
foreach (i RANGE 7)
math (EXPR nibble "${number} & 15")
string (SUBSTRING "${chars}" "${nibble}" 1 nibble_hex)
string (APPEND hex "${nibble_hex}")
math (EXPR number "${number} >> 4")
endforeach ()
string (REGEX REPLACE "(.)(.)" "\\2\\1" hex "${hex}")
set ("${output}" "${hex}" PARENT_SCOPE)
endfunction ()