Converting int to char in C

后端 未结 7 522
不知归路
不知归路 2021-01-18 03:55

Right now I am trying to convert an int to a char in C programming. After doing research, I found that I should be able to do it like this:

int value = 10;
c         


        
相关标签:
7条回答
  • 2021-01-18 04:27

    to convert int to char you do not have to do anything

    char x;
    int y;
    
    
    /* do something */
    
    x = y;
    

    only one int to char value as the printable (usually ASCII) digit like in your example:

    const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    int inttochar(int val, int base)
    {
        return digits[val % base];
    }
    

    if you want to convert to the string (char *) then you need to use any of the stansdard functions like sprintf, itoa, ltoa, utoa, ultoa .... or write one yourself:

    char *reverse(char *str);
    const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    char *convert(int number, char *buff, int base)
    {
        char *result = (buff == NULL || base > strlen(digits) || base < 2) ? NULL : buff;
        char sign = 0;
    
    
        if (number < 0)
        {
             sign = '-';
    
        }
        if (result != NULL)
        {
            do
            {
                *buff++ = digits[abs(number % (base ))];
                number /= base;
            } while (number);
            if(sign) *buff++ = sign;
            if (!*result) *buff++ = '0';
            *buff = 0;
            reverse(result);
        }
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题