View previous topic :: View next topic |
Author |
Message |
Foppie
Joined: 16 Sep 2005 Posts: 138 Location: The Netherlands
|
code efficiency question |
Posted: Fri Sep 16, 2005 3:23 am |
|
|
Hello,
I just started coding on a pic16f877a and I am not experienced with coding on such devices. So I am looking to many resources and that is what I did on the next occasion.
I had to write 10 databits, one after another, to an external bus. I all examples I saw there were bitwise shifting operations, but I didn't like them because they were not readable enough for me (yes, I didn't understand exactly when I first saw them, but I do now). So I decided to give it another approach.
I wrote the next code for it:
Code: |
//write 10 databits
for(i = 512; i >= 1; i = i / 2)
{
SPI_writebit(i == (data & i));
}
|
A few days later I came across the bit_test() method and that made me questioning my code. My question therefor is:
What do you think is the best (most efficient) code?
1: code with bitwise shifting operations
2: my code
3: code using the bit_test() method
4: anything else? |
|
|
asmallri
Joined: 12 Aug 2004 Posts: 1634 Location: Perth, Australia
|
|
Posted: Fri Sep 16, 2005 4:50 am |
|
|
//write 10 databits
for(i = 0b1000000000; i; i >= 1)
SPI_writebit (data & i); _________________ Regards, Andrew
http://www.brushelectronics.com/software
Home of Ethernet, SD card and Encrypted Serial Bootloaders for PICs!! |
|
|
Foppie
Joined: 16 Sep 2005 Posts: 138 Location: The Netherlands
|
|
Posted: Fri Sep 16, 2005 5:03 am |
|
|
asmallri wrote: | for(i = 0b1000000000; i; i >= 1) |
This looks very interesting, but how does the forloop work exactly? I can not see it decreasing in any way (or must >>= be used instead of >=?). And when does the loop stop?
It is in either case something I haven't thought off so thanks! |
|
|
Ttelmah Guest
|
|
Posted: Fri Sep 16, 2005 5:47 am |
|
|
Yes. >>= is needed instead of >=. Posters here are human, and will make typing errors. I do it all the time, when posting a short example.
The nice thing about this, is that you are reducing the amount of maths involved in the whole loop, performing just one operation (the shift), and stopping when the bit shifts out the end of the mask.
Best Wishes |
|
|
Foppie
Joined: 16 Sep 2005 Posts: 138 Location: The Netherlands
|
|
Posted: Fri Sep 16, 2005 6:03 am |
|
|
now I see it, thank you both! |
|
|
|