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

后端 未结 12 1020
深忆病人
深忆病人 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:12

    Just spent time writing this based on answers here, so thought I would share.

    This is based on Brannon's answer, but lets you get more than one digit at a time. In my case I use it to extract parts from a date and time saved in an int where the digits are in yyyymmddhhnnssm_s format.

    public static int GetDigits(this int number, int highestDigit, int numDigits)
    {
        return (number / (int)Math.Pow(10, highestDigit - numDigits)) % (int)Math.Pow(10, numDigits);
    }
    

    I made it an extension, you might not want to, but here is sample usage:

    int i = 20010607;
    string year = i.GetDigits(8,4).ToString();
    string month = i.GetDigits(4,2).ToString();
    string day = i.GetDigits(2,2).ToString();
    

    results:

    year = 2001

    month = 6

    day = 7

提交回复
热议问题