Shift left problems

Thread Starter

spinnaker

Joined Oct 29, 2009
7,830
In the C18 compiler I have the following:

unsigned int sector;
unsigned long arg;

sector = 129;
arg = (sector << 9);

I would expect arg to be equal to 66,048 after this call but it is equal to 512.

It seems to be treating arg like an unsinged int.


What am I doing wrong?
 

THE_RB

Joined Feb 11, 2008
5,438
It's probably because unsigned int sector is 16bit?

If you must use a 16bit var for sectors, then try change your code to this;

sector = 129;
arg = sector; // assign 16bit to 32bit BEFORE math
arg = (arg << 9);
 

Thread Starter

spinnaker

Joined Oct 29, 2009
7,830
It's probably because unsigned int sector is 16bit?

If you must use a 16bit var for sectors, then try change your code to this;

sector = 129;
arg = sector; // assign 16bit to 32bit BEFORE math
arg = (arg << 9);

Thanks that appears to work.
 

codehead

Joined Nov 28, 2011
57
Thanks that appears to work.
Spinnaker—C doesn't look on the left side of the "=" to see where you're trying to go. So if you tell it to shift a 16-bit int, then assign it to a 32-bit long, that's what you'll get—the 16-bit int is shifted, then extended to a long for the assignment. Joeyd999's solution of casting it to long first would have worked for you also.
 
Top