Incorrect bitwise results?

Post Reply
Author
Message
MickeyReilley
Posts: 9
Joined: 02 Oct 2022 22:38

Incorrect bitwise results?

#1 Post by MickeyReilley » 24 Oct 2022 19:11

I'm sure I'm making a noob mistake here, but I can't seem to get my bitwise calculations to return the right values. Why are the following two statements not the same? Note that the function being called has defined the variable in question as unsigned long:

Write_SPI_32(0x300000 + 12, 0b10001111000010100000000000000000); //Gives expected result
Write_SPI_32(0x300000 + 12, (2 << 30) | (120 << 21) | (160 << 12)); //Does not give expected result

hexreader
Posts: 1785
Joined: 27 Jun 2010 12:07
Location: England

Re: Incorrect bitwise results?

#2 Post by hexreader » 24 Oct 2022 20:05

Check the help utility "Integer Constants" section

Unless specifically stated, the constant type will be whatever fits according to the table given in the help utility

This means that the constants in (2 << 30) will both be short type (8 bit)

Furthermore, arithmetic will be done as signed integers unless specified differently

This means that the two signed short constants (2 << 30) will result in an unsigned int value.
Since 2 << 30 result will not fit into a signed integer, it gets truncated and only the lower bits survive the truncation

To ensure that all calculations are performed using unsigned long values, specify the constant size explicitly
Like this:

Code: Select all

    Write_SPI_32(0x300000 + 12, 0b10001111000010100000000000000000);            // Gives expected result for 32-bit unsigned arithmetic
    Write_SPI_32(0x300000 + 12, (2UL << 30) | (120UL << 21) | (160UL << 12));   // force calculations to be unsigned long, rather than 16-bit signed arithmetic
Start every day with a smile...... (get it over with) :)

MickeyReilley
Posts: 9
Joined: 02 Oct 2022 22:38

Re: Incorrect bitwise results?

#3 Post by MickeyReilley » 24 Oct 2022 21:27

Excellent, thank you. Using the "ul" suffix or an (unsigned long) prefix does the trick. #stilllearning

Post Reply

Return to “dsPIC Compilers General”