Skip to content

Instantly share code, notes, and snippets.

@plantpurecode
Created February 14, 2021 15:42
Show Gist options
  • Save plantpurecode/f605660cc6054e3be1726b509267be2c to your computer and use it in GitHub Desktop.
Save plantpurecode/f605660cc6054e3be1726b509267be2c to your computer and use it in GitHub Desktop.
A C implementation of stdlib's itoa function
//
// itoa.c
// itoa
//
// Created by Jacob Relkin on 14/02/2021.
//
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void jr_itoa(int i, char *buffer) {
if (i == 0) {
buffer[0] = '0';
return;
}
int negative = (int)(i < 0);
int x = abs(i);
int digitCount = (int)floor(log(x) / log(10)) + 1;
int index = 0;
if (negative) {
digitCount += 1;
index += 1;
buffer[0] = '-';
}
while (x > 0) {
int digit = x % 10;
int offset = (digitCount - 1 - index) + negative;
buffer[offset] = digit + '0';
index += 1;
x /= 10;
}
buffer[index] = '\0';
}
int main(int argc, const char * argv[]) {
char itoa[20];
jr_itoa(-5, itoa);
printf("%s\n", itoa);
jr_itoa(450, itoa);
printf("%s\n", itoa);
jr_itoa(500, itoa);
printf("%s\n", itoa);
jr_itoa(-122222, itoa);
printf("%s\n", itoa);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment