Nothing is everything.

Wednesday, December 16, 2009

How to convert a char to a digit efficiently

We often need to allow the user to input a digit(0~9). We can call getch() method to get the char, because it is fast. But when we convert it to a digit, it becomes a little complicated, since we need to build a string and call atoi.

There is a simple and efficient method to achieve this:
int digit = getchar() & 0xF.

These are the binary formats of the digits:
0: 11 0000
1: 11 0001
...

0xF: 00 1111

So this calculation will remove the high bits and only leave the lower four bits, these bits formed a new integer, which is just the digit we need.

1 comment:

Followers