Easy Tutorial
❮ Zookeeper Data Sync Verilog Fft ❯

C Language Integer to String and String to Integer Conversion

Category Programming Techniques

1. Overview

In C, conversion between integers and strings can be achieved using widely available extension functions (not part of the standard library) or by implementing simple custom methods.


2. Integer to String

1. Extension Function itoa

itoa (stands for integer to alphanumeric) is a function that converts an integer to a string.

In a Windows environment, it is available in the <stdlib.h> header file:

char* itoa(int value, char* string, int radix); // value: integer to convert, string: converted string, radix: base for conversion (e.g., 2, 8, 10, 16)

Function Source Code:

char* itoa(int num, char* str, int radix)
{
    char index[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Index table
    unsigned unum; // Holds the absolute value of the integer to convert, which might be negative
    int i = 0, j, k; // i indicates the position in the string, k is used for adjusting the order, j for swapping during adjustment

    // Get the absolute value of the integer
    if (radix == 10 && num < 0) // If converting to a decimal and the number is negative
    {
        unum = (unsigned)-num; // Assign the absolute value to unum
        str[i++] = '-'; // Set the first character to '-' and increment the index
    }
    else unum = (unsigned)num; // If num is positive, directly assign it to unum

    // Conversion part, note that the result is in reverse order
    do
    {
        str[i++] = index[unum % (unsigned)radix]; // Get the last digit of unum and assign it to the corresponding position in str
        unum /= radix; // Remove the last digit from unum
    } while (unum); // Continue until unum is 0

    str[i] = '\0'; // Add the null terminator at the end of the string

    // Adjust the order
    if (str[0] == '-') k = 1; // If negative, the sign does not need adjustment, start from the next position
    else k = 0; // If positive, adjust the entire string

    char temp; // Temporary variable for swapping
    for (j = k; j <= (i - 1) / 2; j++) // Swap symmetrically from start to middle
    {
        temp = str[j]; // Assign the start value to temp
        str[j] = str[i - 1 + k - j]; // Assign the end value to the start
        str[i - 1 + k - j] = temp; // Assign the temp value (original start value) to the end
    }

    return str; // Return the converted string
}

Example Program:

#include <stdlib.h>
#include <stdio.h>
int main()
{
    int number1 = 123456;
    int number2 = -123456;
    char string[16] = {0};
    itoa(number1, string, 10);
    printf("Number: %d converted to string: %s\n", number1, string);
    itoa(number2, string, 10);
    printf("Number: %d converted to string: %s\n", number2, string);
    return 0;
}

Screenshot of the Output:


2. Simple Custom Implementation

Implementation Code:

#include <stdio.h>

char* Int2String(int num, char *str); // Function declaration
int main()
{
    int number1 = 123456;
    int number2 = -123456;
    char string[16] = {0};
    Int2String(number1, string);
    printf("Number: %d converted to string: %s\n", number1, string);
    Int2String(number2, string);
    printf("Number: %d converted to string: %s\n", number2, string);
    return 0;
}

char* Int2String(int num, char *str) // Decimal conversion
{
    int i = 0; // Indicator for filling the string
    if (num < 0) // If num is negative, make it positive
    {
        num = -num;
        str[i++] = '-';
    }
    // Conversion
    do
    {
        str[i++] = num % 10 + 48; // Get the last digit of num and convert it to the corresponding ASCII character
        num /= 10; // Remove the last digit from num
    } while (num); // Continue until num is 0

    str[i] = '\0'; // Add the null terminator at the end of the string

    // Adjust the order
    int j = 0;
    if (str[0] == '-') // If there is a negative sign, it does not need adjustment
    {
        j = 1; // Start adjusting from the second character
        ++i; // The symmetry axis should be moved one position forward due to the negative sign
    }
    // Symmetric swap
    for (; j < i / 2; j++)
    {
        str[j] = str[j] + str[i - 1 - j];
        str[i - 1 - j] = str[j] - str[i - 1 - j];
        str[j] = str[j] - str[i - 1 - j];
    }

    return str; // Return the converted string
}

Screenshot of the Output:


3. String to Integer

1. Extension Function

atoi (stands for alphanumeric to integer) is a function that converts a string to an integer.

In a Windows environment, it is available in the <stdlib.h> header file.

int atoi(const char *nptr); // Function to convert string to integer, nptr: string to convert

Function Source Code:

int atoi(const char *nptr)
{
    return (int)atol(nptr);
}

long atol(const char *nptr)
{
    int c; // Current character to convert
    long total; // Current conversion result
    int sign; // Flag indicating if the result is negative

    // Skip spaces
    while (isspace((int)(unsigned char)*nptr))
        ++nptr;

    c = (int)(unsigned char)*nptr++; // Get the next character to convert
    sign = c; // Save the sign indicator
    if (c == '-' || c == '+')
        c = (int)(unsigned char)*nptr++; // Skip the sign character

    total = 0; // Initialize the conversion result to 0

    while (isdigit(c)) { // If the character is a digit
        total = 10 * total + (c - '0'); // Convert the character to its corresponding digit and accumulate
        c = (int)(unsigned char)*nptr++; // Get the next character
    }

    // Return the result based on the sign
    if (sign == '-')
        return -total;
    else
        return total;
}

Example Program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("String \"123456\" converted to number: %d\n", atoi("123456"));
    printf("String \"-123456\" converted to number: %d\n", atoi("-123456"));
    return 0;
}

2. Simple Custom Implementation

Implementation Code:

#include <stdio.h>

int String2Int(char *str); // Function declaration
int main()
{
    printf("String \"123456\" converted to number: %d\n", String2Int("123456"));
    printf("String \"-123456\" converted to number: %d\n", String2Int("-123456"));
    return 0;
}

int String2Int(char *str) // String to integer conversion
{
    char flag = '+'; // Indicator for the sign of the result
    long res = 0;

    if (*str == '-') // If the string has a negative sign
    {
        ++str; // Move to the next character
        flag = '-'; // Set the flag to negative
    }
    // Convert each character and accumulate the result
    while (*str >= 48 && *str <= 57) // If the character is a digit (ASCII 48-57)
    {
        res = 10 * res + (*str++ - 48); // Convert the character to its corresponding digit and accumulate
    }

    if (flag == '-') // If the result is negative
    {
        res = -res;
    }

    return (int)res;
}

Screenshot of the Output:


4. Using sprintf() and sscanf() Functions

Integer to String

Test Code:

#include <stdio.h>

char* Int2String(int num, char *str); // Function declaration
int main()
{
    int number1 = 123456;
    int number2 = -123456;
    char string[16] = {0};
    Int2String(number1, string);
    printf("Number: %d converted to string: %s\n", number1, string);
    Int2String(number2, string);
    printf("Number: %d converted to string: %s\n", number2, string);
    return 0;
}
char* Int2String(int num, char *str)
{
    sprintf(str, "%d", num);
    return str;
}

String to Integer Conversion

Test Code:

Example

#include <stdio.h>

int String2Int(char *str); // Function declaration
int main()
{
    printf("String \"123456\" converted to number: %d\n", String2Int("123456"));
    printf("String \"-123456\" converted to number: %d\n", String2Int("-123456"));
    return 0;
}

int String2Int(char *str) // String to number conversion
{
    char flag = '+'; // Indicates if the result is signed
    long res = 0;

    if (*str == '-') // String has a negative sign
    {
        ++str; // Move to the next character
        flag = '-'; // Set the flag to negative
    }

    sscanf(str, "%ld", &res);
    if (flag == '-')
    {
        res = -res;
    }
    return (int)res;
}

ASCII Table (Partial)


Author: Genven_Liang

Original: https://blog.csdn.net/nanfeibuyi/article/details/80811498

Click to Share Notes

Cancel

-

-

-

❮ Zookeeper Data Sync Verilog Fft ❯