Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Algorithms
  4. algorithm to get each individual digit from a decimal number (integer)

algorithm to get each individual digit from a decimal number (integer)

Scheduled Pinned Locked Moved Algorithms
algorithmshelptutorial
25 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Dr Walt Fair PE

    "Best" in what way? Since I have no specifications, I'd probably use something quick and dirty like

    int n = 1024; // given number
    int d = 2; // digit number, d < n.ToString().Length
    int ds = int.Parse(n.ToString().Substring(d,1));

    etc.

    CQ de W5ALT

    Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

    A Offline
    A Offline
    ant damage
    wrote on last edited by
    #4

    I forgot to mention that I was working on arduino

    D 1 Reply Last reply
    0
    • A ant damage

      I forgot to mention that I was working on arduino

      D Offline
      D Offline
      Dr Walt Fair PE
      wrote on last edited by
      #5

      Ahh, now we have some specifications! :laugh:

      CQ de W5ALT

      Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

      1 Reply Last reply
      0
      • A ant damage

        Hi I need help to find the best snippet to extract individual digits from an integer. Here is an example of what I want to do:

        int number = 1024; //this is the number I want to split into digits
        int digit1 = 1;
        int digit2 = 0;
        int digit3 = 2;
        int digit4 = 4;

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #6

        like others have said, a loop containing a modulo 10 and a divide by 10, are what is required. Assembly programming may give access to an instruction that does both operations in one, something higher-level languages typically don't exploit. You probably don't want any leading zeroes, so you should exit the loop as soon as the quotient is zero, but you still need to output the current remainder, i.e. the test belongs at the bottom of the loop as you want at least one digit. Keep in mind that the number has to be positive for all of this to work correctly; for negative numbers, you need to "negate" first. :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


        I only read formatted code with indentation, so please use PRE tags for code snippets.


        I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


        A 2 Replies Last reply
        0
        • L Luc Pattyn

          like others have said, a loop containing a modulo 10 and a divide by 10, are what is required. Assembly programming may give access to an instruction that does both operations in one, something higher-level languages typically don't exploit. You probably don't want any leading zeroes, so you should exit the loop as soon as the quotient is zero, but you still need to output the current remainder, i.e. the test belongs at the bottom of the loop as you want at least one digit. Keep in mind that the number has to be positive for all of this to work correctly; for negative numbers, you need to "negate" first. :)

          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


          I only read formatted code with indentation, so please use PRE tags for code snippets.


          I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


          A Offline
          A Offline
          ant damage
          wrote on last edited by
          #7

          After a long trying, I found this snippet:

          int number = 1024;
          int digit1 = ((number / 1000) % 10);
          int digit2 = ((number / 100) % 10);
          int digit3 = ((number / 10) % 10);
          int digit4 = ((number / 1) % 10); //dividing by 1 is useless, only to show

          M 1 Reply Last reply
          0
          • A ant damage

            After a long trying, I found this snippet:

            int number = 1024;
            int digit1 = ((number / 1000) % 10);
            int digit2 = ((number / 100) % 10);
            int digit3 = ((number / 10) % 10);
            int digit4 = ((number / 1) % 10); //dividing by 1 is useless, only to show

            M Offline
            M Offline
            molesworth
            wrote on last edited by
            #8

            ant-damage wrote:

            After a long trying, I found this snippet:

            ... which is great until you give it a number like 456789. Or if you try it with 23, you'll end up with zeroes. As others have said, a loop will work no matter what number you throw at it.

            Days spent at sea are not deducted from one's alloted span - Phoenician proverb

            A 1 Reply Last reply
            0
            • A ant damage

              Hi I need help to find the best snippet to extract individual digits from an integer. Here is an example of what I want to do:

              int number = 1024; //this is the number I want to split into digits
              int digit1 = 1;
              int digit2 = 0;
              int digit3 = 2;
              int digit4 = 4;

              C Offline
              C Offline
              CPallini
              wrote on last edited by
              #9

              we call it sprintf. (Does Arduino provide it?) :)

              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
              This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
              [My articles]

              L 1 Reply Last reply
              0
              • C CPallini

                we call it sprintf. (Does Arduino provide it?) :)

                If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                [My articles]

                L Offline
                L Offline
                Luc Pattyn
                wrote on last edited by
                #10

                unfortunately that is not an algorithm, nor the name of an algorithm. however, if it is meant as a suggestion to have a look at an sprintf implementation, it is a valid one, as there are umpteen implementations available; almost any microprocessor vendor or open source kernel offers one. :)

                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                I only read formatted code with indentation, so please use PRE tags for code snippets.


                I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                C 1 Reply Last reply
                0
                • L Luc Pattyn

                  unfortunately that is not an algorithm, nor the name of an algorithm. however, if it is meant as a suggestion to have a look at an sprintf implementation, it is a valid one, as there are umpteen implementations available; almost any microprocessor vendor or open source kernel offers one. :)

                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                  I only read formatted code with indentation, so please use PRE tags for code snippets.


                  I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                  C Offline
                  C Offline
                  CPallini
                  wrote on last edited by
                  #11

                  Luc Pattyn wrote:

                  unfortunately that is not an algorithm, nor the name of an algorithm.

                  I know. :zzz:

                  Luc Pattyn wrote:

                  almost any microprocessor vendor or open source kernel offers one.

                  That's the point, there's no need to look at the function implementation details (well, actually there is "curiosity"), my suggestion was: "use sprintf" that is already optimized (the algorithm then becomes trivial, just subtract '0' to every character...). :)

                  If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                  This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                  [My articles]

                  T 1 Reply Last reply
                  0
                  • C CPallini

                    Luc Pattyn wrote:

                    unfortunately that is not an algorithm, nor the name of an algorithm.

                    I know. :zzz:

                    Luc Pattyn wrote:

                    almost any microprocessor vendor or open source kernel offers one.

                    That's the point, there's no need to look at the function implementation details (well, actually there is "curiosity"), my suggestion was: "use sprintf" that is already optimized (the algorithm then becomes trivial, just subtract '0' to every character...). :)

                    If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                    This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                    [My articles]

                    T Offline
                    T Offline
                    theCPkid
                    wrote on last edited by
                    #12

                    isn't sprintf language specific? Unless the OP has very good knowledge of C or in case he is programming in some high level language like python, your answer will be greek to him. Consider explaining the 'optimized' algorithm of sprintf to him instead...

                    C 1 Reply Last reply
                    0
                    • T theCPkid

                      isn't sprintf language specific? Unless the OP has very good knowledge of C or in case he is programming in some high level language like python, your answer will be greek to him. Consider explaining the 'optimized' algorithm of sprintf to him instead...

                      C Offline
                      C Offline
                      CPallini
                      wrote on last edited by
                      #13

                      Wow, now I see the OP convincing Arduino it can run Python code... :laugh:

                      If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                      This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                      [My articles]

                      A 1 Reply Last reply
                      0
                      • C CPallini

                        Wow, now I see the OP convincing Arduino it can run Python code... :laugh:

                        If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                        This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                        [My articles]

                        A Offline
                        A Offline
                        ant damage
                        wrote on last edited by
                        #14

                        I use C++ to make programs for my arduino Of course, arduino's library collection includes sprintf() in stdio.h By the way it is a c++ compiler

                        C 1 Reply Last reply
                        0
                        • M molesworth

                          ant-damage wrote:

                          After a long trying, I found this snippet:

                          ... which is great until you give it a number like 456789. Or if you try it with 23, you'll end up with zeroes. As others have said, a loop will work no matter what number you throw at it.

                          Days spent at sea are not deducted from one's alloted span - Phoenician proverb

                          A Offline
                          A Offline
                          ant damage
                          wrote on last edited by
                          #15

                          You were right. I've just created a test program to see if that piece of code was doing its paper. I made the test so that it writes to a file the number of failed comparisions. The result file had 200MB of length, so I think it's better to create a new algorithm to do that

                          1 Reply Last reply
                          0
                          • A ant damage

                            I use C++ to make programs for my arduino Of course, arduino's library collection includes sprintf() in stdio.h By the way it is a c++ compiler

                            C Offline
                            C Offline
                            CPallini
                            wrote on last edited by
                            #16

                            ant-damage wrote:

                            I use C++ to make programs for my arduino

                            ant-damage wrote:

                            By the way it is a c++ compiler

                            Did you use C++? :-D

                            If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                            This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                            [My articles]

                            A 1 Reply Last reply
                            0
                            • C CPallini

                              ant-damage wrote:

                              I use C++ to make programs for my arduino

                              ant-damage wrote:

                              By the way it is a c++ compiler

                              Did you use C++? :-D

                              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                              This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                              [My articles]

                              A Offline
                              A Offline
                              ant damage
                              wrote on last edited by
                              #17

                              of course I do Which programming language could be better to be used along the arduino? C++

                              1 Reply Last reply
                              0
                              • L Luc Pattyn

                                like others have said, a loop containing a modulo 10 and a divide by 10, are what is required. Assembly programming may give access to an instruction that does both operations in one, something higher-level languages typically don't exploit. You probably don't want any leading zeroes, so you should exit the loop as soon as the quotient is zero, but you still need to output the current remainder, i.e. the test belongs at the bottom of the loop as you want at least one digit. Keep in mind that the number has to be positive for all of this to work correctly; for negative numbers, you need to "negate" first. :)

                                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                I only read formatted code with indentation, so please use PRE tags for code snippets.


                                I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                                A Offline
                                A Offline
                                ant damage
                                wrote on last edited by
                                #18

                                Please show me an example of what you saying. I'm not american nor british.

                                L 1 Reply Last reply
                                0
                                • A ant damage

                                  Please show me an example of what you saying. I'm not american nor british.

                                  L Offline
                                  L Offline
                                  Luc Pattyn
                                  wrote on last edited by
                                  #19

                                  ant-damage wrote:

                                  I'm not american nor british

                                  I'll give you an example implementation in pseudo-code then:

                                  arrayOfInts ToDigits(int value) {
                                  bool negative=value<0;
                                  if (negative) value=-value;
                                  ListOfInts digits=new ListOfInts;
                                  do {
                                  int mod=value%10;
                                  digits.Add(mod);
                                  value/=10;
                                  } while (value!=0);
                                  if (negative) digits.Add(specialCodeForMinusSign);
                                  return digits.Reverse.ToArray;
                                  }

                                  PS: I am aware it would fail when fed int.MinValue :)

                                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                  I only read formatted code with indentation, so please use PRE tags for code snippets.


                                  I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                                  A 1 Reply Last reply
                                  0
                                  • L Luc Pattyn

                                    ant-damage wrote:

                                    I'm not american nor british

                                    I'll give you an example implementation in pseudo-code then:

                                    arrayOfInts ToDigits(int value) {
                                    bool negative=value<0;
                                    if (negative) value=-value;
                                    ListOfInts digits=new ListOfInts;
                                    do {
                                    int mod=value%10;
                                    digits.Add(mod);
                                    value/=10;
                                    } while (value!=0);
                                    if (negative) digits.Add(specialCodeForMinusSign);
                                    return digits.Reverse.ToArray;
                                    }

                                    PS: I am aware it would fail when fed int.MinValue :)

                                    Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                    I only read formatted code with indentation, so please use PRE tags for code snippets.


                                    I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                                    A Offline
                                    A Offline
                                    ant damage
                                    wrote on last edited by
                                    #20

                                    What the purpose of this algorithm? Do you ever saw those 7-segment led displays in your tv, stereo hi-fi, vcr or dvd? I have one of those but with 4 digits in one display, and those digits are in multiplexed mode, so I can only iterate with one at a time. I won't use negative numbers, because I will use that display to make a digital counter/timer. By the way, thanks for the example. I'm now ready to create an optimized one.

                                    L 2 Replies Last reply
                                    0
                                    • A ant damage

                                      What the purpose of this algorithm? Do you ever saw those 7-segment led displays in your tv, stereo hi-fi, vcr or dvd? I have one of those but with 4 digits in one display, and those digits are in multiplexed mode, so I can only iterate with one at a time. I won't use negative numbers, because I will use that display to make a digital counter/timer. By the way, thanks for the example. I'm now ready to create an optimized one.

                                      L Offline
                                      L Offline
                                      Luc Pattyn
                                      wrote on last edited by
                                      #21

                                      Oh great. This thread holds 20 messages already, and now you come with some details. I'm out of here. X|

                                      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                      I only read formatted code with indentation, so please use PRE tags for code snippets.


                                      I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                                      1 Reply Last reply
                                      0
                                      • A ant damage

                                        What the purpose of this algorithm? Do you ever saw those 7-segment led displays in your tv, stereo hi-fi, vcr or dvd? I have one of those but with 4 digits in one display, and those digits are in multiplexed mode, so I can only iterate with one at a time. I won't use negative numbers, because I will use that display to make a digital counter/timer. By the way, thanks for the example. I'm now ready to create an optimized one.

                                        L Offline
                                        L Offline
                                        Luc Pattyn
                                        wrote on last edited by
                                        #22

                                        Please don't remove messages that have replies attached; it is against the forum guidelines. I copied your original question here: Hi I need help to find the best snippet to extract individual digits from an integer. Here is an example of what I want to do:

                                        int number = 1024; //this is the number I want to split into digits
                                        int digit1 = 1;
                                        int digit2 = 0;
                                        int digit3 = 2;
                                        int digit4 = 4;

                                        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                        I only read formatted code with indentation, so please use PRE tags for code snippets.


                                        I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                                        T 1 Reply Last reply
                                        0
                                        • D Dr Walt Fair PE

                                          "Best" in what way? Since I have no specifications, I'd probably use something quick and dirty like

                                          int n = 1024; // given number
                                          int d = 2; // digit number, d < n.ToString().Length
                                          int ds = int.Parse(n.ToString().Substring(d,1));

                                          etc.

                                          CQ de W5ALT

                                          Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software

                                          A Offline
                                          A Offline
                                          Anshul R
                                          wrote on last edited by
                                          #23

                                          Convert the number to string Loop through the characters, store it. Eg : <pre> Dim digits As New ArrayList For Each digit As Char in CStr(number) digits.Add(CInt(digit)) End For </pre>

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups