Converting a number to different notation

This is a program for converting numbers to different representations, such as octal, decimal, hexadecimal, etc.

    #include<stdio.h>

    char *convert(unsigned int num, int base)
    {
    static char buff[33];
    char *ptr;
    ptr=&buff[sizeof(buff)-1];
    *ptr='\0';
    do
    {
    *--ptr="0123456789abcdef"[num%base];
    num/=base;
    }while(num!=0);
    return(ptr);
    }

    int main(){

    puts(convert(65,8));
    puts(convert(65,10));
    puts(convert(65,16));
    return 0;
    }

The output gives 101, 65, and 41 (that is, the number "65" is represented in octal, decimal, and hexadecimal notation, respectively)

I pretty much understand what is going on, but I have never come across anything like

*--ptr="0123456789abcdef"[num%base]

I understand his work, but I do not understand how this is a valid notation. Someone please explain here part 0123456789abcdef (literal array of characters).

+5
source share
3 answers

; , , , IOCCC ( C-).

*--ptr = "0123456789abcdef"[num%base];

, . :

const char digit[] = "0123456789ABCDEF";
*--ptr = digit[num%base];

. . ( , , :

*--ptr = (num % base)["0123456789ABCDEF"];

:

a[i] <==> i[a] <==> *(a + i) <==> *(i + a)

.

*--ptr - , . , ( , , ).

, , . :

printf("%s = %s = %sn", convert(65,8), convert(65,10), convert(65,16));

, , , "101", "164" "140" , "01", "64" "40" , C, . .

, . , , . , convert(65, 18) undefined. ( 17 '\0', , .)

+9

, . , , .

*--ptr = : " ".

"0123456789abcdef" - char.

[num%base] char, num base.

, , , :

char arr[] = "0123456789abcdef";
int subscript = num % base;
ptr = ptr - 1;
*ptr = arr[subscript];
+4

-

char array[]="0123456789abcdef";
*--ptr=array[num%base];
+1
source

All Articles