SA-MP Forums Archive
Returning a single character from a string, returns as a int?(bit operate - Printable Version

+- SA-MP Forums Archive (https://sampforum.blast.hk)
+-- Forum: SA-MP Scripting and Plugins (https://sampforum.blast.hk/forumdisplay.php?fid=8)
+--- Forum: Scripting Help (https://sampforum.blast.hk/forumdisplay.php?fid=12)
+--- Thread: Returning a single character from a string, returns as a int?(bit operate (/showthread.php?tid=492301)



Returning a single character from a string, returns as a int?(bit operate - Hoborific - 03.02.2014

So yeah, I have this stock

pawn Код:
stock GetFirstNumber(number)
{
    new
        number_str[12],
        bool: negative;
   
    if (number < 0) negative = true;
    valstr(number_str, number);
    return (negative) ? (number_str[1]) : (number_str[0]);
}
I pass it something between 1000 and 2000 and I get 49, I pass it something above 2000 and I get 50, and so forth. I was wondering why it's returning such strange numbers and if there's something wrong with the stock..

I've checked the integer i'm passing it, it's correct..


Re: Returning a single character from a string, returns as a int?(bit operate - Vince - 03.02.2014

This is because the textual representation of a number is different than the number itself. See here: http://www.asciitable.com/index/asciifull.gif
The textual representation of the number 2 is 50, which is exactly what you're describing. You need strval to reconvert it to the numerical value. Not sure if there's better way to do it.


Re: Returning a single character from a string, returns as a int?(bit operate - Hoborific - 03.02.2014

I should have remembered this from the awful time I spent with VB, thank you very much.


Re: Returning a single character from a string, returns as a int?(bit operate - Misiur - 03.02.2014

Operations on strings are quite slow, just do something like
pawn Код:
stock FirstDigit(n) {
    new
        digit = 0;
       
    n *= n < 0 ? -1 : 1;

    do {
        digit = n % 10;
        n /= 10;
    } while (n > 0);
   
    return digit;
}



Re: Returning a single character from a string, returns as a int?(bit operate - Hoborific - 03.02.2014

Would you mind explaining the code though?


Re: Returning a single character from a string, returns as a int?(bit operate - Misiur - 03.02.2014

Sure thing:
pawn Код:
stock FirstDigit(n) {
    new
        digit = 0;
       
    //First thing - get the absolute value of n
    //(in fact that's a little better version)
    if(n < 0) n = -n;

    do {
        //Get the modulus of n, returning last digit
        //(we can't jump straight to first though :c)
        //So for 1245 it will be 5
        digit = n % 10;
       
        //Remove last digit (it's an integer, so it doesn't have fractions - insta flooring)
        //1245 => 124
        n /= 10;

        //Do so until there are no more digits left
    } while (n > 0);
   
    return digit;
}