Search code examples
cmicrocontrolleravr

Convert integer char[] to hex char[] avr microcontroller


I'm looking to convert a input variable of this type:

char var[] = "9876543210000"

to a hex equivalent char

char hex[] = "08FB8FD98210"

I can perform this by e.g. the following code::

long long int freq;
char hex[12];
freq = strtoll(var,NULL,10);
sprintf(hex, "%llX",freq);

However I'm doing this on a avr microcontroller, thus strtoll is not available only strtol (avr-libgcc). So I'm restricted to 32 bits integer which is not enough. Any ideas?

Best regards Simon


Solution

  • Yes.... this method works fine only with positive number, so if you have a minus sign, just save it before doing next. Just divide the string number in two halves, lets say that you select six digit each, to get two decimal numbers: u_int32_t left_part; and u_int32_t right_part; with the two halves of your number.... you can construct your 64 bit number as follows:

    u_int64_t number = (u_int64_t) left_part * 1000000 + right_part;
    

    If you have the same problem on the printing side, that is, you cannot print but 32 bit hex numbers, you can just get left_part = number >> 32; and right_part = number & 0xffffffff; and finally print both with:

    if (left_part) printf("%x%08x", left_part, right_part);
    else printf("%x", right_part);
    

    the test makes result not to be forced to 8 digits when it is less than 0x100000000.