Search code examples
cintegerasciiuart

C: Splitting integer and converting it to ASCII


I would like to split integer into digits and then convert each digit to ASCII (in C programming language).

Example:

int x = 0xABC
/* split integers */
int x1 = 0xA
int x2 = 0xB
int x3 = 0xC
/* convert integers to ASCII */
int x1 = 0x41
int x2 = 0x42
int x3 = 0x43

Also, if the integer is only 2 digits long (hex), I still need 3 splits:

int y = 0xBC
/* split integers */
int y1 = 0x0
int y2 = 0xB
int y3 = 0xC 
.
.
.

Many thanks in advance!


Solution

  • Use math: x = x₁ · 16² + x₂ · 16 + x₃

    Use a lookup table to see what the digit is:

    static const char hex[16] = "0123456789ABCDEF";
    
    y1 = hex[x1];
    ...
    

    I won't give you a full solution since it's a homework related question.


    Full solution (less easy to understand):

    // Divide by 16^n and take the modulo 16:
    int x1 = (x >> 8) & 0xF; // == (x/256) % 16
    int x2 = (x >> 4) & 0xF; // == (x/16) % 16
    int x3 = (x >> 0) & 0xF; // == x % 16
    
    int y1 = x1 < 10 ? x1+'0' : x1+'A'-10;
    int y2 = x2 < 10 ? x2+'0' : x2+'A'-10;
    int y3 = x3 < 10 ? x3+'0' : x3+'A'-10;