Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Design a program that converts decimal to octal, such as inputting 10 and outputting 12. Thank you.

in C language

Design a program that converts decimal to octal, such as inputting 10 and outputting 12. Thank you.

in C language

#include

#include

/************** *************************************************** *********

Function: Convert non-negative decimal integer to octal character processing function

Parameter: int num: decimal number; char *ptr :Save the converted octal string

Return: ptr (the first address of the array that saves the string)

************** *************************************************** *********/

char *dec_to_oct(unsigned long num,char *ptr);

int main(void)

{

//for test

char str[12];

int num=0;

char *p;

printf("You can enter several non-negative integers continuously:");

while(1)

{

scanf("%d" ,&num);

if(num<0)

break;

p = dec_to_oct(num,str);

/ /printf("strlen(str)=%d\n",strlen(p));

printf("Dec:%d = Oct:%s\n",num,p);< /p>

}

return 0;

}

char *dec_to_oct(unsigned long num,char *ptr)

{

unsigned long n=num;

int i=0;

int j=0;

unsigned long tmp;

char ch;

while((n/8)!=0){

tmp = n%8;

ch =tmp + '0';

*(ptr+i)=ch;

n = n/8;

i++;

< p>}

tmp = n%8;

ch = tmp + '0';

*(ptr+i)=ch;

i++;

*(ptr+i)='\0';

/*Because the highest bit of oct is at the end of the array and the lowest bit is at the beginning of the array, the order is reversed Character array*/

tmp = i/2;

j = 0;

i--;

while(j< tmp)

{

ch = *(ptr+j);

*(ptr+j)=*(ptr+i);

*(ptr+i) = ch;

i--;

j++;

}

return ptr ;

}