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
Incorrect bitwise results?
Re: Incorrect bitwise results?
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:
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)
-
- Posts: 9
- Joined: 02 Oct 2022 22:38
Re: Incorrect bitwise results?
Excellent, thank you. Using the "ul" suffix or an (unsigned long) prefix does the trick. #stilllearning