Register.SetBits() gives "Argument 1: cannot convert from 'int' to 'uint'"

I feel like I’m missing something really obvious here, and if that is the case, I will apologize profusely :slight_smile: … until that happens, I’m hoping somebody on this forum can help me out …

I have code uses the internal TIMx timers of the Cerbuino Bee.

The following is an example of code that works exactly as I would expect …


MyTIMRegister.SetBits(1 << 0 | 1 << 4); //This sets Bits 0 and 4 in the register

However, when I want to set the left-most bit in the register (Bit 31), I do this:


MyTIMRegister.SetBits(1 << 31); 

And I get a compiler error "Error 2 Argument 1: cannot convert from ‘int’ to ‘uint’ RegisterUtilities.cs 137 33 MotorController

Am I missing something obvious here?

Is there an alternate bitmask that will set ONLY the left-most bit to 1?

Just use this:

MyTIMRegister.SetBits((uint)1 << 31)

Actually this one is better:

MyTIMRegister.SetBits(0x80000000)

In addition to @ Architect’s answer, another option is to use the numeric suffix you could use

MyTIMRegister.SetBits(1u << 31);

or

MyTIMRegister.SetBits(1U << 31);

While suffixes can be either upper or lower case, the upper case suffix is usually preffered because l is potentially confused with 1 while L is easily distinguished.

@ Architect - Tx, I marked your answer because it fixes the problem. In hindsight, I can see why also (Visual Studio treats numbers as signed by default).

However, I do have a follow-up question …

Why do you suggest the format “MyTIMRegister.SetBits(0x80000000)” is better?

@ taylorza - Very Elegant … thank you :slight_smile:

@ JackN - It is a pleasure

Essentially the same, but in case there are no compiler optimizations constant is better then an expression.

Two reasons I prefer the (1 << x ) nomenclature

It shows you explicitly what bit you are setting. There is no need to reconvert the 0x80… into figuring out the flag you mean.

If you use a constant for the shift-offset, then you can easily reflect the function of that mask. If your register has to change, you just change your constant.

One reason I can suggest Architect might suggest the 0x80… format is better is because its explicit - it’s an unsigned int and there’s no need to cast it.

In all cases the IL is exactly the same, a constant value is loaded onto the stack. No self respecting compiler would not perform constant folding, even in debug builds. Personally I also favor the (1 << x) version for readability, but that is a personal opinion.