Page 1 of 1

C question

Posted: Thu Jul 03, 2003 1:16 pm
by rosborne
What does this mean?<p>#define ERR (1<<15)<p>specifically the (1<<15) part.<p>Rick

Re: C question

Posted: Thu Jul 03, 2003 2:44 pm
by greg123
#define defines a macro<p>ERR is the name of the macro<p><< is the shift left operator. It's used to shift bits left.<p>So, (1 << 15) is the value of the macro and
1 << 15 means 1 shifted left 15 times i.e. 0x8000<p>
This can be expressed as:<p>unsigned int x = ERR;<p>is the same as<p>unsigned int x = (1 << 15);<p>or<p>unsigned int x = 0x8000;

Re: C question

Posted: Thu Jul 03, 2003 2:49 pm
by rosborne
Ok that makes sense, I still think it is a weird way to define a constant. It threw me.
Rick

Re: C question

Posted: Thu Jul 03, 2003 2:53 pm
by greg123
Well you can exclude the left shift operator, since you are always shifting the 1 15 spaces.<p>You can use:<p>#define ERR 0x8000<p>The left operator should be used when you are shifting another variable.<p>#define ERR (j<<15) where j is a changing variable.<p>greg<p>[ July 03, 2003: Message edited by: Greg ]</p>

Re: C question

Posted: Thu Jul 03, 2003 5:24 pm
by rosborne
Makes sense now, thanks. I just didn't expect a shift operator used to define a constant so I assumed it was something special. It was the only one out of about 30 lines of #define that was done that way. Not the way I'd have done it, but I'm just a hack. Thanks much, probably post more
?s next week.
-Rick

Re: C question

Posted: Thu Jul 03, 2003 8:04 pm
by bodgy
Though not in this case, you'll sometimes see that construct in uP programming where it is used to specify an output pin bit.<p>Such as <p>EPORT^=1<<ebit; or
if (sysflag&(1<<keydown))<p>Here ebit would be a portbit number.<p>In the second example the variable SYSFLAG has individual bits used to signal system flags. KEYDOWN is allocated a constant bit number elsewhere in the program, for example BIT3 therefore SYSFLAG is checked to see whether BIT3 is TRUE(is the same as 1)within the 8 bit variable. If it is, SYSFLAG at a binary level would look like 00001000 that is BIT3==1<p>Colin<p>[ July 03, 2003: Message edited by: bodgy ]</p>

Re: C question

Posted: Sat Jul 05, 2003 12:09 pm
by Will
Does that mean that (i<<15) is actually equal to 0x8000 -how does that work ? I figured that if I shifted a '1' left 15 times then it would be equal to 32768 or 32K ?

Re: C question

Posted: Sat Jul 05, 2003 1:57 pm
by greg123
Will,<p>Your exactly right.<p>0x8000 is equal to 32768.<p>0x signifies that it is a hexadecimal value and 32768 is a decimal value.<p>greg

Re: C question

Posted: Sat Jul 05, 2003 2:20 pm
by Will
Thanks Greg,
I didn't know that 'O' represented Hexdecimal

Re: C question

Posted: Sat Jul 05, 2003 2:33 pm
by greg123
Yeah,<p>It's actually the "0x"