linux内核算法---hex_to_bin分享

这是我从内核抠出来的一段代码,用处就是传入一个字符,即能够用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
",hex_to_bin('1'));
	printf("%d
",hex_to_bin('f'));
	printf("%d
",hex_to_bin('a'));
	printf("%d
",hex_to_bin('9'));
	
	printf("%p
",hex_to_bin('1'));
	printf("%p
",hex_to_bin('f'));
	printf("%p
",hex_to_bin('a'));
	printf("%p
",hex_to_bin('9'));
	return 0 ;
}
执行结果:



原文地址:https://www.cnblogs.com/clnchanpin/p/7098405.html