Problem with "bit" variables

キャンセル
次の結果を表示 
表示  限定  | 次の代わりに検索 
もしかして: 

Problem with "bit" variables

2,060件の閲覧回数
jreyes085
Contributor I

I don´t know if i can do this...This is an example of what i want to do:

 

Bit my_name_function(void) {                  ; i want to return only one bit.

 

byte temp;

 

temp=PTDD;                                         ;temp = port D of the MC, 8 bits.

 

return ((bit)(temp&0x80));                      ;i just want to return the last bit of PTDD

 

}

 

How can i do this? the bit data type doesnt exist in codewarrior as in other compilers...What can i do to do this in codewarrior?

 

thanks

ラベル(1)
0 件の賞賛
返信
3 返答(返信)

514件の閲覧回数
bigmac
Specialist III

Hello,

 

For return of a value, a function must return one of the standard variable types; for this case an unsigned char or byte is the appropriate one. The return value would be loaded to the accumulator register, meaning that all 8 bits will contain a value.

 

The alternative is to return a reference to a bit field, but here the coding would be more complex. The header file for the MCU derivative you are using makes extensive use of bit fields to identify the individual bits of each register.

 

Note that return (PTDD & 0x80); will return zero when the bit is clear, and non-zero when the bit is set, so the following expression should work as expected.

 

if (my_name_function()) {

...

}

 

Actually, you may not need a separate function if you can make use of the bit fields already defined within the header file.  The following example should achieve the same effect, but would apply only to the MCU registers within the header.

 

if (PTDD_PTDD7) {

   ...

}
 

Regards,

Mac

Message Edited by bigmac on 2009-03-02 12:10 PM
0 件の賞賛
返信

514件の閲覧回数
jreyes085
Contributor I

thanks, i finally did that way, using the PTDD_PTDD7 and it works well on simulation.

 

thanks mac...

 

0 件の賞賛
返信

514件の閲覧回数
Lundin
Senior Contributor IV
If you ever want to port the code to another compiler or processor, I would strongly advise against using bit fields. Codewarrior uses non-standard C for its bit fields, and on top of that, bit fields are poorly defined by the standard, making them practically non-portable.

Bitwise operators & and | generate exactly the same op-codes, with the difference that they are standard C and portable to any compiler or computer. If you use bitwise operators, you could for example test the code on a Windows PC (32/64 bit little endian) and then port the very same code to HCS12 or HCS08. If you use bit fields, this is impossible.
0 件の賞賛
返信