标签:blog io ar for 2014 on log amp ef
#include "string.h" #define INVALID_VALUE_LXX ((1 << (8 * sizeof(int) -1)) - 1) /*有符号整型最大值,如果越界将为0, and - is prioty of <<*/ #define A2a(ch) (('a' <= (ch) && (ch) <= 'f') ? (ch) : ((ch) - 'A' + 'a')) bool is0to9(char ch) { if ('0' <= ch && ch <= '9') { return true; } else { return false; } } bool isatoF(char ch) { if (('a' <= ch && ch <= 'f') || ('A' < ch && ch <= 'F')) { return true; } else { return false; } } int a2iLxx(char* ch) { int index = 0; int retVal = 0; bool flag = false; if (NULL == ch) { return INVALID_VALUE_LXX; } /*Ox*/ if ('0' == ch[0] && ('x' == ch[1] || 'X' == ch[1])) { index = 2; for (; ch[index] != '\0'; index++) { /* x * 2^y == x * 1 << y */ if (is0to9(ch[index])) { retVal = (retVal << 4) + ch[index] - '0'; continue; } if (isatoF(ch[index])) { retVal = (retVal << 4) + 10 + A2a(ch[index]) - 'a'; continue; } return INVALID_VALUE_LXX; } return retVal; } /*10*/ index = 0; if ('-' == ch[0]) { /*负数*/ flag = true; index = 1; } for (; ch[index] != '\0'; index++) { if (!is0to9(ch[index])) { return INVALID_VALUE_LXX; } retVal = retVal * 10 + ch[index] - '0'; } if (flag) { return -retVal; } else { return retVal; } } void main() { char ch1[] = "123"; char ch2[] = "-234"; char ch3[] = "0"; char ch4[] = "0x123"; char ch5[] = "0xff"; int a = INVALID_VALUE_LXX; char d1 = A2a('a'); char d2 = A2a('B'); /*调试查看值*/ a = a2iLxx(ch1); a = a2iLxx(ch2); a = a2iLxx(ch3); a = a2iLxx(ch4); a = a2iLxx(ch5); }
字符转整型,比系统的好用!a2iLxx (涵盖 16进制,VC6亲测可用)请提出宝贵意见~
标签:blog io ar for 2014 on log amp ef
原文地址:http://blog.csdn.net/lxx723/article/details/40351295