NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Interpret statement

September 02, 2011
by egero1
egero1's Avatar

I am having trouble interpreting what this line of code is passing: ((keys & 0xF0) << 8) | (keys & 0xF). It is being passed to a function that accepts a word. Is the precedence as follows:

  1. keys & 0xF0
  2. << 8 result
  3. keys & 0xF
  4. | result with result from step 2

Thanks, Eric

September 02, 2011
by bretm
bretm's Avatar

Every pair of operands has parenthesis around it, so is there any other way to interpret it? The order might be different (it could do 3 before 1 and 2) but the result will be the same as your order.

Apparently it takes an 8-bit key and turns it into a 16-bit number with the same 4 most-significant bits and same 4 least-significant bits and the middle 8 bits empty.

a b c d e f g h  ->  a b c d 0 0 0 0 0 0 0 0 e f g h
September 02, 2011
by BobaMosfet
BobaMosfet's Avatar

egero1

It adds the values of keys to 0xF0 (240d) and then shifts the value left 8 bits. In that order, because of the perand nesting.

Whether or not it turns it into a 16 bit number, or just shifts the data out of the byte, depends on what this value is being assigned to, and whether or not values are signed or not.

BM

September 02, 2011
by bretm
bretm's Avatar

In C, the type of an expression never depends on the type of the variable that it is being assigned to. An expression's type is independent of that, the program evaluates it independently, and only after the result is completely determined is the value cast to a different type as needed.

Example: uint32 x = y * z. If y and z are uint16, the expression is uint16 and the operation is performed using uint16 multiplication and will overflow and wrap around to 0 if the result exceeds the uint16 max value.

I used the word "apparently" in my response because that was my best guess about the types involved.

The shifting will never shift it out of the byte because the shift operator casts its left operand to 16 bits if it is only 8 bits to start with. If the upper 8 bits are lost after assignment, that's not a result of the shifting but is a result of the casting.

Left shifting behavior does not depend on signed-ness of the operand type like right shifting does.

September 03, 2011
by egero1
egero1's Avatar

Thanks for the replies. I did not realize that the shift operator casts the left operand, but that is very good to know.

Eric

Post a Reply

Please log in to post a reply.

Did you know that an analog comparator can tell when one voltage input crosses another? Learn more...