Author Topic: Routines to convert binary to BCD in C code  (Read 3609 times)

0 Members and 2 Guests are viewing this topic.

Offline cv007

  • Frequent Contributor
  • **
  • Posts: 828
Re: Routines to convert binary to BCD in C code
« Reply #25 on: April 26, 2024, 06:51:49 pm »
Quote
and dumped the count by UART every second
That is one of the points I am making- speed of conversion does not matter at all if outputting only every second. Even when you want to dump lots of (formatted) data it matters very little.

You original post was focused on the conversion speed, but if you had actually output all the data at your specified 9600 baud (960 bytes/sec) you would have found out that any formatting you can come up with will be blocking on the uart as it sends out the data, whether you used the arduino print which you had access to or your own custom bcd conversion.

Do what you desire, but using existing code for formatting such as printf or arduino print will be plenty fast. Code size will also be of little concern unless you have a 4k or less mcu. In the case of an avr, the printf code is about 1.5k and once brought in you can use it as much as you want (so use it for everything that needs formatting). For arduino (which I don't use) I imagine no one using that will concern themselves with how the details of formatting are done as they just use print when the need arises.

printf( "%lu\n", my10MHzCounter() ); //%lu for 32bits on avr
Serial.println( my10MHzCounter() );

 

Offline PicuinoTopic starter

  • Frequent Contributor
  • **
  • Posts: 774
  • Country: 00
    • Picuino web
Re: Routines to convert binary to BCD in C code
« Reply #26 on: April 26, 2024, 07:10:21 pm »
In this project, the problem was to print 48-bit numbers (16 bits of the main uC counter + 32 bits of the carry counter) in decimal (15 decimal digits).
In that case the speed was not important, but to be able to do conversions of many bits. I solved it with custom subroutines for 48bit bit-shift and the algorithm I have previously published.
With a 32-bit microcontroller it is simple, but with an 8-bit microcontroller you have to do the job differently.
« Last Edit: April 26, 2024, 07:12:16 pm by Picuino »
 

Offline cv007

  • Frequent Contributor
  • **
  • Posts: 828
Re: Routines to convert binary to BCD in C code
« Reply #27 on: April 26, 2024, 10:29:25 pm »
Quote
but with an 8-bit microcontroller you have to do the job differently.
Differently, but can still use the tools already in the toolbox.

uint64_t v = readCount();
uint32_t vH = v / 1000000000u;
uint32_t vL = v % 1000000000u;
//skip leading 0's, avr lu is uint32_t
if( vH ) print( "%lu%09lu\n", vH, vL ); else print ( "%lu\n", vL );

 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf