How to convert single char to long in c

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sreeharibabu
    New Member
    • Feb 2014
    • 1

    #1

    How to convert single char to long in c

    Ex :
    Char x='2';
    long out=0;
    out=atol(x);

    here i want to get out value as 2 but it is not happening
    Now out value get 0 . Please suggest as soon as ossible
  • stdq
    New Member
    • Apr 2013
    • 94

    #2
    Hello! I think you could do a cast:

    Code:
    #include <stdio.h>
    
    int main( void )
    {
        char x = '2';
        long int out = ( long int )x;
        
        printf( "%ld\n", out );
    }
    However, be careful, because '2' is a character whose decimal value in ASCII is 50, so the output of this code will be 50.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      So just code:

      Code:
      char x=2;
      long out=0;
      out= x;
      A char and a long are both integers so you can assign the char to the long. The compiler won't object because the long is larger than the char. You just can't go the other way without getting a warning from the compiler about possible loss of data.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        The problem is that atol expects a char* not a char. I'm surprised the code you posted even compiles, I am sure it doesn't compile without warnings.

        You could just take a pointer to your char
        Code:
        out=atol(&x);
        Problem with that is atol doesn't just expect a char* it expects a pointer to a C string, that is a zero terminated array of char which you do not have you have a single char. You could convert it to a string

        Code:
        char buffer[2];
        buffer[0] = x;
        buffer[1] = '\0';
        out=atol(buffer);
        But personally I find it rather long winded. As long as you are sure there is a digit character in your variable then you can just rely on the language guarantee that digit character values are contiguous (i.e. '1' = '0' + 1 ...)

        Code:
        out= x - '0';

        Comment

        Working...