Home > Mobile >  Pep8 number decomposition
Pep8 number decomposition

Time:10-07

i'm trying to decompose a number in pep8 into thousands digit, followed by a part that represents the digit hundreds, followed by a part that represents the tens digit, and finally a part which represents the ones digit.

exemple: the number 439 should be decomposed this way 0,4,3,9.

Do you have any tips ?

CodePudding user response:

How is the number 439 being stored?  Is it a string, or a numeric value stored in binary somewhere?

What constraints do you have?  If you know the number is always < 10,000 and always non-negative, you can make some simplifying choices.

Also, you need to consider whether you want numeric 0,4,3,9 or string form "0439".

The following post has many good answers, especially for small processors that don't have hardware divide or mod:  https://electronics.stackexchange.com/questions/12618/fastest-way-to-get-integer-mod-10-and-integer-divide-10

There are several approaches:

  1. something involving division or mod by some power(s) of 10 to extract individual digits

    • similar to the above but with substitutions for division or mod by 10 using subtraction, shifting, and other; this answer shows a simple way to extract digits from non-negative number using subtraction instead of division https://electronics.stackexchange.com/a/91940
  2. conversion of binary numbers to BCD; a BCD number has each decimal digit isolated.  This category more or less translates the whole number from binary to BCD, from that you can relatively simply extract individual digits
    https://electronics.stackexchange.com/a/112455

You can also search for algorithms called itoa — which stands for integer to ascii.  If you have an individual decimal digit isolated (as with some of the above), it can be converted ascii character e.g. for printing, by adding 48, which is the ascii code for '0' — the printable character for the digit zero.  This works b/c the character codes for the decimal digits are consecutive so 9 48 = 57, which is '9'.

  • Related