HOW TO CONVERT STRING to INT without using any inbuilt functions..??

Hi all,

How to Convert my String str=10 into int s=10; without using any inbuilt libraries like parse or convert to int etc. I had this question in interview...but i tried something in binary level but not accepted.pls clarify how internally data conversion takes place...

thanks.

Maheshkumar.R

www.snipurl.com/guac




Answer this question

HOW TO CONVERT STRING to INT without using any inbuilt functions..??

  • natarius

    Thank you so much john..I hope you wont mind to share any links for other datatype conversion also..I mean for float, decimal,..etc..THanks for clearing my curiosity..

    Mahesh



  • wigga

    they're just testing your logic and problem solving skills. and of course, how deep is your understanding about the language. they want to know if you are dependent on the language. you should also learn the root of the language.

  • Bill Cumming

    Hey ;) Believe it or not, once there were programming languages where you had to do stuff like this yourself ;)
  • Alan M.

    Jhon let me try myself. Ok. Let me try to convert int - > string

    int i=00;

    string str="";

    by string should have char right... 051 048 048 ..how to split the int to char....pls give some clue regarding this..

    Mahes



  • pete_smith74

    Well, it is always the same principle. To convert a number from the decimal system you take the last digit:
    int digit = number % 10;
    Where number is the number to convert and by modulo 10, you get the last digit. Then you add this digit as the leading character to the string. Now you divide the number by 10:
    number /= 10;
    Repeat the these 3 steps: mod 10, add character, div 10 until the number to convert is 0. If you exchange the 10, e.g. by 2 you would convert the number into a binary version.

     


  • Peter Svensson

    well, i never had an interview like this, but I guess they want to see you doing it manually ;)

    somehow like this:

    string sx = "10";
    int ix = 0;
    for (int i=0; i<sx.Length; i++)
    {
      ix *= 10;
      ix += sx[ i ]-48;
    }


  • Vinayakg

    Of course in practice no-one in their right mind would do this in a real app.

    I suspect if this was being asked as an interview question, the interviewer was looking for you to consider things like:

    - how to handle signs in the input string
    - how to handle overflow if the string of digits is too large to fit into an integer.


  • HOW TO CONVERT STRING to INT without using any inbuilt functions..??