gur111 icon

dec2base4

gur111 | PRO | 08/09/19 09:06:19 PM UTC | 0 ⭐ | 490 👁️ | Never ⏰ | []
C |

740 B

|

None

|

0 👍

/

0 👎

/* Converts base dec to base4. Returns as string */
char* dec2base4(unsigned long num){
    /* Allocates memory for output string */
    char *out = malloc(MAX_NUM_SIZE);
    /* The charset of the output base */
    char dict[4] = {'0','1','2','3'};
    int i;
    /* Set ALL chars to "0" (or first in charset) so characters that we won't
        reach will not be skipped */
    memset(out, dict[0], MAX_NUM_SIZE);
    /* Let's not forget about NULL string termination */
    out[MAX_NUM_SIZE-1] = '\0';
    for(i = 0; num; i++, num=num>>2){
        /* The magic: Takes the last 2 bin digits of num and take the
            coresponding char from the charset */
        out[MAX_NUM_SIZE-2-i] = dict[num&3];
    }
    
    return out;
}

Comments