Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Type cast and/or integer promotion problem in C

Status
Not open for further replies.

Fearsome

Newbie level 6
Joined
Nov 30, 2009
Messages
11
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
Sweden
Activity points
1,392
--------------------------------------------------------------------------------
I have a routine that converts from two's complement to a float. The first thing I want to do is combine the most significant byte and least significant byte of the output of a sensor to one unsigned int. I may not be experienced in C but I thought I did understand type conversions. Here's a part of the code:


Code:
float ConvTwosComp(unsigned char LS, unsigned char MS) {
	unsigned int temp;

	temp = ((unsigned int) MS)<<8 + (unsigned int) LS;

                //...More code that actually converts temp to float.
}



What I wanted to do was to convert MS to an unsigned int and left shift it and then add LS. From my understanding of integer promotion, the type cast of LS shouldn't even be needed. However, this conversion doesn't work! What am I doing wrong?

Fred
 

Operator precedence!
You need to move the bracket.

temp = ((unsigned int) MS)<<8 + (unsigned int) LS;

temp = ( (unsigned int)MS << 8 ) + LS;
 

So you're saying that the shift is done before the type cast?

Fred
 

Where the rest of the conversion code?
 

The addition is done before the shift! So you shift 8 + LS places.
 

Is it left to right precedence?
 

Mostly it's left to right, but for some operators, it's right to left, the rules can be found in your compiler docs.
It's not order in your case, + and - come before << >> no matter what order there in.
 

If it is left to right I guess shift will be performed first.
Am I right?
 

No, your not right,
+ and - come before << or >> no matter what order there in.
 

Ok I got it.
I would live to try it myself later.
 

amraldo said:
Where the rest of the conversion code?

Is the rest of the conversion code interesting to you? I didn't post it since it isn't relevant to my question. The conversion is for a 16 bit sign-extended two's complement word from a DS18B20 temp sensor. I convert to a float. Let me know if you want that particular code snippet.

Fred
 

I was thinking the rest of the code had the error but btbass clarified where the problem was.
 

I suggest to stick a table with ANSI C operators precedence to the wall.
Seriously you can't remember it completely.

 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top