View previous topic :: View next topic |
Author |
Message |
mtsoule
Joined: 19 Oct 2011 Posts: 31
|
Using printf to convert int to octal |
Posted: Wed Feb 01, 2017 11:51 am |
|
|
My goal is to convert an int to octal, I know I can use printf to convert to hex.
But when I try the below code, it will not compile,
Code: |
*** Error 115 "main.c" Line 158(37,45): Printf format (%) invalid ::
|
I thought this would be easily done by
Code: |
Main_Sec = 59;
printf("d: %x | %o \r", Main_Sec, Main_Sec);
|
It seems the compiler does not support this part of printf. Am I correct? Will I have to write a function to do the conversion, or am I missing something in printf?
Thanks |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
|
mtsoule
Joined: 19 Oct 2011 Posts: 31
|
|
Posted: Wed Feb 01, 2017 12:40 pm |
|
|
That was the first thing I did was consult the manual. and there was no mention of octal, so I assumed it did not support it.
However, I had to at least try the old C types, and not surprisingly it didn't work. Was just hoping there was something I was missing. But I guess not.
Thanks
interestingly, Scanf does support octal.. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Feb 01, 2017 2:49 pm |
|
|
Here is one solution, provided by 'aaz' here:
http://stackoverflow.com/questions/5361719/decimal-to-octal-in-c
It's in the section that begins with 'With loops you can roll up'.
I truncated it to work with 0 to 255 as input values.
This test program will convert decimal numbers from 0 to 255 to
octal numbers 0 to 377. This was tested in MPLAB vs. 8.92 simulator.
Code: |
#include <18F46K22.h>
#fuses INTRC_IO,NOWDT,PUT,BROWNOUT
#use delay(clock=4M)
#use rs232(baud=9600, UART1, ERRORS)
void print_octal(int8 num)
{
int8 div;
for(div = 64; div > 0; div /= 8)
printf("%u", num / div % 8);
putc('\r');
}
//=====================================
void main(void)
{
int8 i;
// Convert decimal 0 to 255 to octal and print it.
do{
print_octal(i);
}while(i++ != 255);
while(TRUE);
} |
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19546
|
|
Posted: Thu Feb 02, 2017 1:40 am |
|
|
itoa.....
Generic function to convert an integer (up to int32), to any base 'n'.
Code: |
#include <stdlib.h> //needed somewhere
int16 val=200; //test value
char result[6]; //where the result is to go
itoa(val,8,result); //converts 'val' to base 8 (octal)
//result now contains the octal string "310"
|
|
|
|
|