``return((int)ADHR << 2);``

im trying to learn what a certain function does and then i stumble upon this part. i do get that << 2 means shift left by 2. what i do not know is the (int)ADHR part. can anyone help me out with this? thank you

4
Contributors
7
Replies
10
Views
8 Years
Discussion Span
Last Post by iwanttolearnc

ADHR should be, by convention, a defined global variable or constant, (thus the all caps). First that value (defines in C are a straight substitution) is left shifted two places, then the result is cast as an integer.

Finally that value is returned from the function.

thank you sir. one more thing to clarify, say ADHR contains a binary word for example 1110001. left shifting this 2 places to the left will give me 1000100 right? what happens when it is "cast as an integer"?

N << 2 Is a logical shift left, 2 bits. There is no arithmetic left shift! Same as a multiplication x4

N >> 2 Is a logical shift right 2 bits if N is unsigned integer. Div 4
N >> 2 is an arithmetic shift right 2 bits if N is a signed integer.

The difference between an arithmetic shift and a logical shift is the MSB (Most Significant Bit) is what I refer to as a sticky bit. The MSB is preserved why shifting to the right. A logical right shift clocks in a zero into the MSB.

Edited by wildgoose: n/a

thank you very much for those that replied.
sadly i still do not get the part with the (int)ADHR. thank you again

If ADHR is a #define then the shift (x4) is done at compile time. If ADHR is a variable then it is done at run time.

I think the type cast has to be done before applying the shift operator. Here is an example to show why

``````int main()
{
float f= 5.67;
int x= (int)f<<2;
printf("%d\n",x);
return 0;
}``````

If f is not typecasted before applying the shift operator then the code will not compile as shift operators cannot be applied to floating point numbers.
This code does compile and produces the answer 20

thank you very much sirs!