如何使用宏而非函数提取包含在另一个数字中的数字。
示例伪代码:
#define extract_number(int number, // original number
int pos, // start position from behind (1 == first digit)
int len) // count of digits
{
...
}
main() {
int number = 0;
int result = 0;
number = 123456789;
result = extract_number(number, 2, 3); // result: 678
number = 987123456;
result = extract_number(number, 4, 4); // result: 7123
}
编辑21.09.2016: 我做的atm如下:
int number = 123456789;
int result = number / 10 % 1000;
使用@Frzn Flms发布的函数的版本是我在函数中完成它的方式。有没有办法在编译时使用宏来做?
答案 0 :(得分:0)
例如:2应替换为10,3应替换为1000。
使用boost编写如下。
#include <stdio.h>
#include <boost/preprocessor/control/while.hpp>
#include <boost/preprocessor/arithmetic/add.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/cat.hpp>
#define PRED(d, state) BOOST_PP_TUPLE_ELEM(2, 0, state)
#define OP(d, state) (BOOST_PP_DEC(BOOST_PP_TUPLE_ELEM(2, 0, state)), BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(2, 1, state), 0))
#define pow0(n) BOOST_PP_TUPLE_ELEM(2, 1, BOOST_PP_WHILE(PRED, OP, (BOOST_PP_ADD(n,1), 1)))
int main(void) {
int n = pow0(2);//1000: "1" + "0"✕(n+1)
printf("%d\n", n);
return 0;
}