Skip to main content

Type Conversion & Casting

For most languages you should avoid implicit convertion or using only the simple type casting.

// ------------------------------------
// String to Number
// ------------------------------------

// AVOID atoi() and its counterparts (Check More Info)

// Prefer strtol()
char *endPointer;
long convertedValue = strtol("123", &endPointer, 10);

if (*endPointer != '\0')
{
// Conversion did not consume the full string
}

// Base 10
long convertedValue = strtol("123", NULL, 10);

// Base 16
long convertedValue = strtol("FF", NULL, 16);

// ------------------------------------
// Floating number to Integer
// ------------------------------------

#include <math.h> // For floor(), ceil(), round()

// It returns a floating type, so you need a cast.
int convertedValue = (int) floor(5.5); // Must include <math.h>
int convertedValue = (int) ceil(5.5); // Must include <math.h>
int convertedValue = (int) round(5.5); // Must include <math.h>
// ------------------------------------
// Number to String
// ------------------------------------

// Example creating a function using snprintf()
#include <stdio.h> // For snprintf()
#include <stdlib.h> // For malloc(), free()

char* IntToString(int value)
{
int length = snprintf( NULL, 0, "%d", value );

char* converted = malloc( length + 1 ); // one character more for null-terminator
snprintf( converted, length + 1, "%d", value );

return converted;
}

// Another simple example
char* FloatToString(float value)
{
float length = snprintf( NULL, 0, "%f", value );

char* converted = malloc( length + 1 ); // one character more for null-terminator
snprintf( converted, length + 1, "%f", value );

return converted;
}

char* convertedValue = IntToString(100);
// ...
free(convertedValue); // You need to free the memory allocated by malloc()

More Info: