linux内核算法---hex_to_bin分享

来源:互联网 发布:c seo的伪静态 编辑:程序博客网 时间:2024/06/14 10:43

这是我从内核抠出来的一段代码,用处就是传入一个字符,即可以用printf语句%d以十进制数的格式输出,同时也可以以%p地址的形式输出。

        代码如下:

#include <stdio.h>#include <stdlib.h>#include <ctype.h>#define  tolower(c)  __tolower(c)#define  toupper(c)  __toupper(c)static  inline unsigned char __tolower(unsigned char c){//判断字符c是否为大写英文字母 说明:当参数c为大写英文字母(A-Z)时,返回非零值,否则返回零。if(isupper(c))c -= 'A' - 'a' ;return c ;}static inline unsigned char __toupper(unsigned char c ){//判断字符c是否为小写英文字母 说明:当参数c为小写英文字母(a-z)时,返回非零值,否则返回零。if(islower(c))c-= 'a' - 'A' ;return c ;}int hex_to_bin(char ch){if((ch > '0') && (ch <= '9'))return ch - '0' ;ch = tolower(ch) ;if((ch >= 'a') && (ch <= 'f'))return ch - 'a' + 10 ;return -1 ;}int main(void){printf("%d\n",hex_to_bin('1'));printf("%d\n",hex_to_bin('f'));printf("%d\n",hex_to_bin('a'));printf("%d\n",hex_to_bin('9'));printf("%p\n",hex_to_bin('1'));printf("%p\n",hex_to_bin('f'));printf("%p\n",hex_to_bin('a'));printf("%p\n",hex_to_bin('9'));return 0 ;}
运行结果:



0 0