casting a char to an int, weird result

Discussion in 'C' started by rabidusv, Jul 25, 2006.

  1. rabidusv

    rabidusv New Member

    Joined:
    Jul 25, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    I'm receiving data from a socket into a char[] and am casting each member of the array to an int. Some of the char's when casted into an int yield the character '-' I'm not sure what to make of this, has anyone ever experienced or heard of anything like this?
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Can you post the code here so that we can look into it.

    Thanks
    Shabbir.
     
  3. rabidusv

    rabidusv New Member

    Joined:
    Jul 25, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Actually I figured it out a couple minutes ago. It was because the array of characters was signed, changed it to an unsigned char array and that solved it. Thanks for the quick reply!!
     
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    My pleasure.
     
  5. goldnlink

    goldnlink New Member

    Joined:
    Jul 27, 2006
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    UK
    Home Page:
    http://goldnlink.com
    Hi rabidusv,
    I would just add that in order to conver a char into an int, you'll have to use the function atoi.
    Example:
    int number;
    char character = '1';
    number = atoi(&character);

    You could now use this function to extend it to convert a full string (char*) into a number.
    Pay attention when converting like you are doing. Remember that '0' has the value 48, not 0. However, atoi(&char) if char = '0' is 0. :)
    regards
    goldnlink
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice