Can someone explain this?

Status
Not open for further replies.

Pommie

Well-Known Member
Most Helpful Member
I know there's got to be a simple explanation but I can't see it,
I thought all these would be the same, I'm trying to put 51 in the highest byte of work.
Code:
uint32_t work;

  work=51*(2^24);

  work=51<<24;

  work=51;
  work<<=24;
but when the result is printed out, I get,
1326
0
855638016
The actual code,
Code:
uint32_t work;

void setup(){
  Serial.begin(115200);
  work=51*(2^24);
  Serial.println(work);
  work=51<<24;
  Serial.println(work);
  work=51;
  work<<=24;
  Serial.println(work);
}

void loop(){
  
}

What am I missing?

Thanks,

Mike.
 
Try using 51L to force a long constant?

Any intermediate math may be done as integer, otherwise.
 
Yup, that fixed it except for the first one, even doing,
work=51L*(2L^24L);
And all other combos,
Doesn't fix it - answer is 1326!!!!

Mike.
 
And also for,
work=(2L^24);
and
work=(2^24);
It appears that the compiler is taking ^ as +.
Just tried,
work=(2^20);
and it gives 22!!!


Mike.
 
Looks like a compiler bug!
It explains the 1326 result, at least.

Does the same thing happen with small powers, eg. 2^3 ?
 
^ is a bitwise xor on the arduino ...

(51<<24) is the way they do it or pow();
 
Yup! just checked.. constants are 16 bit unless u, l or ul are specified
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…