How to get the Nth digit of an integer with bit-wise operations?

后端 未结 12 1022
深忆病人
深忆病人 2021-01-30 21:23

Example. 123456, and we want the third from the right (\'4\') out.

The idea in practise is to access each digit seperately (ie. 6 5 4 3 2 1).

C/C++/C# preferred.

12条回答
  •  孤独总比滥情好
    2021-01-30 22:08

    The reason that it won't work (easily) with bit-wise operations is that the base of the decimal system (10) is not a power of the base of the binary system (2).

    If you were coding in base 8, you'd have pow(2, 3) == 8, and could extract each octal digit as a block of three bits.

    So you really have to convert to base 10, which is usually done by converting to a string (with toString (Java) or sprintf (C), as the others have shown in their replies).

提交回复
热议问题