Shift left problems

Discussion in 'Embedded Systems and Microcontrollers' started by spinnaker, Jan 11, 2012.

  1. spinnaker

    Thread Starter AAC Fanatic!

    Oct 29, 2009
    4,866
    988
    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?
     
  2. joeyd999

    AAC Fanatic!

    Jun 6, 2011
    2,674
    2,717
    perhaps:

    arg = ((unsigned long)sector) << 9;
     
  3. THE_RB

    AAC Fanatic!

    Feb 11, 2008
    5,435
    1,305
    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);
     
    spinnaker likes this.
  4. spinnaker

    Thread Starter AAC Fanatic!

    Oct 29, 2009
    4,866
    988

    Thanks that appears to work.
     
  5. codehead

    Member

    Nov 28, 2011
    56
    11
    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.
     
    joeyd999 likes this.
Loading...