Best way to get single digits from int for sorting radix in C / C ++

What is the best way to get single digits from an int with n number of digits to use in the numbering sorting algorithm? I am wondering if there is a particularly good way to do this in C / C ++, if not what is the general best solution?

edit: just for clarification, I looked for a solution other than converting it to a string, and saw it as an array of numbers.

+5
source share
2 answers

Use size digits 2^k. To extract the digit nth:

#define BASE (2<<k)
#define MASK (BASE-1)

inline unsigned get_digit(unsigned word, int n) {
    return (word >> (n*k)) & MASK;
}

Using a shift and mask (using a base which is a power of 2) avoids costly integer instructions.

- ( ). , k==3 ( 8) , k==4 ( 16) , . , , , , 32 64 . , , , .

: , , , . , , , radix , 1 0. , , , k .

+6

10, 16.

for (int i = 0; i < 8; i++) {
    printf("%d\n", (n >> (i*4)) & 0xf);
}

, , 10 .

+3

All Articles