It is seems very easy to implement c library function
So what to do?
There are many similar functions like
Source code of
An example of this trick : How to reverse a byte’s bit as fast as possible? For example, convert ‘00010001’ to ‘10001000’.
isdigit
, but for a library code, performance is very important. So we will try to implement it and make it faster.Function
So, first we make it right.int isdigit(char c) {
return c >= '0' && c <= '9';
}
Improvements
One – Macro
When it comes to performance for c code, macro can always be tried.#define isdigit(c) c >= '0' && c <= '9'
Two – Table
Upper version use two comparison and one logical operation, but we can do better with more space:#define isdigit(c) table[c]
This works and faster, but somewhat wasteful. We need only one bit to represent true or false, but we use a int. So what to do?
There are many similar functions like
isalpha(), isupper ...
in c header file, so we can combine them into one int and get result by table[c]&SOME_BIT
, which is what source do.Source code of
ctype.h
:# define _ISbit(bit) (1 << (bit))
// mask of table
enum
{
_ISupper = _ISbit (0), /* UPPERCASE. */
_ISlower = _ISbit (1), /* lowercase. */
_ISalpha = _ISbit (2), /* Alphabetic. */
_ISdigit = _ISbit (3), /* Numeric. */
_ISxdigit = _ISbit (4), /* Hexadecimal numeric. */
_ISspace = _ISbit (5), /* Whitespace. */
_ISprint = _ISbit (6), /* Printing. */
_ISgraph = _ISbit (7), /* Graphical. */
_ISblank = _ISbit (8), /* Blank (usually SPC and TAB). */
_IScntrl = _ISbit (9), /* Control character. */
_ISpunct = _ISbit (10), /* Punctuation. */
_ISalnum = _ISbit (11) /* Alphanumeric. */
};
// __ctype_b_loc is the table with result
# define __isctype(c, type) \
((*__ctype_b_loc ())[(int) (c)] &
(unsigned short int) type)
# define isdigit(c) __isctype((c), _ISdigit)
Conclusion
When we deal with char/byte and require very fast implementation, use a table with result pre-computed is a good solution.An example of this trick : How to reverse a byte’s bit as fast as possible? For example, convert ‘00010001’ to ‘10001000’.
Written with StackEdit.
评论
发表评论