Skip to content

Instantly share code, notes, and snippets.

@mentix02
Last active November 3, 2024 12:35
Show Gist options
  • Save mentix02/70f4dcd4d22030779b5ccbffbee30cc4 to your computer and use it in GitHub Desktop.
Save mentix02/70f4dcd4d22030779b5ccbffbee30cc4 to your computer and use it in GitHub Desktop.
Simple conversion lib
#include "conv.h"
#include <string.h>
uint64_t toUint64T(const char * nstr) {
uint8_t digit;
uint64_t res = 0;
for (size_t i = 0; i < strlen(nstr); ++i) {
digit = nstr[i] - '0';
res = res * 10 + digit;
}
return res;
}
uint32_t toUint32T(const char * nstr) {
return (uint32_t) toUint64T(nstr);
}
size_t toSizeT(const char * nstr) {
return (size_t) toUint64T(nstr);
}
int64_t toInt64T(const char * nstr) {
int64_t res = 0;
uint8_t digit, sign = 1;
if (nstr[0] == '-') {
sign = -1;
nstr++;
}
for (size_t i = 0; i < strlen(nstr); ++i) {
digit = nstr[i] - '0';
res = res * 10 + digit;
}
return res * sign;
}
int32_t toInt32T(const char * nstr) {
return (int32_t) toInt64T(nstr);
}
#ifndef CONV_H
#define CONV_H
#include <stdint.h>
#include <stddef.h>
size_t toSizeT(const char *);
uint32_t toUint32T(const char *);
uint64_t toUint64T(const char *);
int32_t toInt32T(const char *);
int64_t toInt64T(const char *);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment