Search code examples
ccharlong-integer

c - Long Long to char conversion function in embedded system


Im working with a embedded system and I need implement a way to convert long long to char.

The problem is that I can not use sprintf in this system to do that, so im looking for alternative ways/functions to implement this.

Suggestions of implementations for LongLongToChar function are welcome.


Solution

  • Google "itoa". There are many variations. Here's an example.

    char* itoa(int val, int base){
    
        static char buf[32] = {0};
    
        int i = 30;
    
        for(; val && i ; --i, val /= base)
    
            buf[i] = "0123456789abcdef"[val % base];
    
        return &buf[i+1];
    
    }
    

    Specifically, here's an 'lltoa'.

    #include <stdio.h>
    #include <limits.h>
    
    
    char* lltoa(long long val, int base){
    
        static char buf[64] = {0};
    
        int i = 62;
        int sign = (val < 0);
        if(sign) val = -val;
    
        if(val == 0) return "0";
    
        for(; val && i ; --i, val /= base) {
            buf[i] = "0123456789abcdef"[val % base];
        }
    
        if(sign) {
            buf[i--] = '-';
        }
        return &buf[i+1];
    
    }
    
    int main() {
        long long a = LLONG_MAX;
        long long b = LLONG_MIN + 1;
        long long c = 23;
    
        printf("%ld\n", sizeof(a));
        printf("max '%s'\n", lltoa(a, 10));
        printf("min '%s'\n", lltoa(b, 10));
        printf("-1  '%s'\n", lltoa((long long)-1, 10));
        printf("23  '%s'\n", lltoa(c, 10));
    }