avr-gcc-list
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [avr-gcc-list] storing a float value to a 8-bit registers


From: Joerg Wunsch
Subject: Re: [avr-gcc-list] storing a float value to a 8-bit registers
Date: Tue, 27 May 2003 10:25:23 +0200 (MET DST)

Abhijeet D Mhatre <address@hidden> wrote:

> Is the fact that avr-library stores floats and doubles in 4-bytes,
> documented in any of its manuals or guides.

Sure, just read the FAQ:

http://savannah.nongnu.org/download/avr-libc/doc/avr-libc-user-manual/FAQ.html#faq_reg_usage

(It's in the first paragraph there.)

> I want to display the decibel value ( in double ) for that I will
> have to take it our through the 8 bit ports.  Thats why I wanted to
> load the float/ double in the registers.  If there is a more elegant
> solution please let me know.

#include <inttypes.h>
#include <avr/io.h>

void
print_float(float db)
{
        union {
              float f;
              uint8_t b[sizeof(float) / sizeof(uint8_t)];
        } u;
        uint8_t i;

        u.f = db;
        for (i = 0; i < sizeof(float) / sizeof(uint8_t); i++)
                PORTB = u.b[i];
}

:-))

It's probably more effective though to leave the path that is
guaranteed by standard C, and use ``wild typecasting'' instead:

#include <inttypes.h>
#include <avr/io.h>

void
print_float(float db)
{
        uint8_t *dbp = (uint8_t *)&db;
        uint8_t i;

        for (i = 0; i < sizeof(float) / sizeof(uint8_t); i++)
                PORTB = *dbp++;
}

Note that from a C point of view, that's poor programming style
(conversion of arbitrary pointer types is not a defined operation),
but from a microcontroller programmer's point of view, that yields the
better code.

-- 
J"org Wunsch                                           Unix support engineer
address@hidden        http://www.interface-systems.de/~j/


reply via email to

[Prev in Thread] Current Thread [Next in Thread]