View previous topic :: View next topic |
Author |
Message |
mho Guest
|
C question |
Posted: Wed Jan 14, 2009 7:01 am |
|
|
hi!
i have the next code for I2C:
Code: |
int16 read_it(){
int lsb,msb;
i2c_start();
i2c_write(0xC0);
i2c_write(0x41);
i2c_stop();
delay_ms(7);
i2c_start();
i2c_write(0xC1);
msb = i2c_read();
lsb = i2c_read(0);
i2c_stop();
delay_ms(5);
[b]return((int16)msb|((int16)lsb << 8));[/b]
}
|
but i don't understand the last line, what it return?
thanks |
|
![](templates/subSilver/images/spacer.gif) |
Wayne_
Joined: 10 Oct 2007 Posts: 681
|
|
Posted: Wed Jan 14, 2009 7:13 am |
|
|
return((int16)msb|((int16)lsb << 8));
msb and lsb are both 8 bit values.
the (int16) converts the var to a 16 bit var.
the << 8 shifts the lsb left by 8 bits.
the | symbol ORs the 2 values together.
So in total this converts the 2 8 bit values into a 16 bit value using the lsb as the upper 8 bits and the msb as the lower 8 bits and returns this new 16 bit value.
You have to type cast the 8 bit values to 16 bit values to be able to do this other wise the result will be an 8 bit value and would be wrong. |
|
![](templates/subSilver/images/spacer.gif) |
RLScott
Joined: 10 Jul 2007 Posts: 465
|
Re: C question |
Posted: Wed Jan 14, 2009 7:17 am |
|
|
mho wrote: |
Code: | return((int16)msb|((int16)lsb << 8)); |
...i don't understand the last line, what it return? |
It returns the a 16-bit integer whose low-order byte is msb and whose high order byte is lsb. It seems the variable names msb and lsb are assigned or used backwards, if you think that msb means Most Significant Byte and lsb means Least Significant Byte. _________________ Robert Scott
Real-Time Specialties
Embedded Systems Consulting |
|
![](templates/subSilver/images/spacer.gif) |
Ttelmah Guest
|
|
Posted: Wed Jan 14, 2009 8:50 am |
|
|
As a separate 'comment' though, the CCS compiler has the 'make16' instruction, which is generally more efficient at doing this conversion. Fortunately the optimiser is quite good now, and should automatically replace the 8 bitwise shifts, with a single 'byte' movement.
Best Wishes |
|
![](templates/subSilver/images/spacer.gif) |
Guest
|
Re: C question |
Posted: Wed Jan 14, 2009 9:48 am |
|
|
RLScott wrote: |
It returns the a 16-bit integer whose low-order byte is msb and whose high order byte is lsb. It seems the variable names msb and lsb are assigned or used backwards, if you think that msb means Most Significant Byte and lsb means Least Significant Byte. |
you're right, i've realized that i wrote it bad, it should be
Code: |
return((int16)lsb|((int16)msb << 8)):
|
in that case, could you give me an example??
thanks! |
|
![](templates/subSilver/images/spacer.gif) |
|