//template params:N number digits. S start position
//sample data {0x12, 0x34, 0x56, 0x78, 0x9F} if (N=4,S=1) then result = 2345
template <int N,int S=0>
class bcd_to_int
{
public:
static int parse(char* src)
{
static_assert(sizeof(int)==4, "int must be 4 byte");
static_assert(N <= 10,"int not exceed 10 digits");
static_assert(S==1 || S==0, "S int [0,1]");
char buff[N + 1] = { 0 };
typedef std::conditional<S%2 == 0, std::true_type, std::false_type>::type is_even_type;
parse_helper<N>(src, buff, is_even_type());
return boost::lexical_cast<int>(buff); ;
}
template<int N>
static void parse_helper(char* src, char* buff, std::true_type)
{
buff[0] = ((*src & 0xF0) >> 4) + 0x30;
parse_helper<N-1>(src, buff + 1, std::false_type());
}
template<>
static void parse_helper<0>(char* src, char* buff, std::true_type)
{}
template<int N>
static void parse_helper(char* src, char* buff,std::false_type)
{
buff[0] = (*src & 0x0F) + 0x30;
parse_helper<N-1>(src + 1, buff + 1, std::true_type());
}
template<>
static void parse_helper<0>(char* src, char* buff,std::false_type)
{}
};
int main()
{
char src[] = { 0x89,0x89,0x89,0x89,0x89 };
int ret = bcd_to_int<9>::parse(src); //999999999
//bcd_to_int<10>::parse(src); will throw error
ret = bcd_to_int<3,1>::parse(src); //989
return 0;
}
BCD转int
最新推荐文章于 2024-10-24 08:36:50 发布