Getting part of a number

This is a discussion on Getting part of a number within the C++ Programming forums, part of the General Programming Boards category; I have been wondering about this for a while, is it possible to extract a single digit from a longer ...

  1. #1
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485

    Getting part of a number

    I have been wondering about this for a while, is it possible to extract a single digit from a longer number? Say you have the number 123456, is it possible to just get the second from the front? The only way I can come up with it is to convert the number into a string.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Divide by 10000 and take modulo 10?

    Of course, that assumes the number is 6 digits long. But the same principle holds for any size integer that fits in one of the integer types that your compiler provides.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Feb 2009
    Posts
    42

  4. #4
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,263
    Quote Originally Posted by h3ro View Post
    The only way I can come up with it is to convert the number into a string.
    That's actually not such a bad way of doing it, since sprintf() is going to use the divide-and-modulo method to do the conversion, which is the same thing you would have done anyway. Provided it's easy to create the buffer for the string conversion, I think converting to string and then accessing the digits is not a bad method.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Random number + guessing game trouble
    By Ravens'sWrath in forum C Programming
    Replies: 16
    Last Post: 05-08-2007, 04:33 AM
  2. Stone Age Rumble
    By KONI in forum Contests Board
    Replies: 30
    Last Post: 04-02-2007, 10:53 PM
  3. Replies: 2
    Last Post: 11-18-2006, 03:31 AM
  4. Perfect number...
    By Argo_Jeude in forum C++ Programming
    Replies: 8
    Last Post: 07-12-2005, 02:53 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21