不按预期工作Arduino的左移,编译器错误? [英] Arduino left shift not working as expected, compiler bug?

查看:580
本文介绍了不按预期工作Arduino的左移,编译器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

uint32_t a = 0xFF << 8;
uint32_t b = 0xFF;
uint32_t c = b << 8;

我编译为乌诺(1.0.x的和1.5)和它似乎明显,'一'和'c'应该是相同的值,但它们不是......至少不上运行时目标。我编译主机上的同一code和没有的问题。

I'm compiling for the Uno (1.0.x and 1.5) and it would seem obvious that 'a' and 'c' should be the same value, but they are not... at least not when running on the target. I compile the same code on the host and have no issues.

右移工作正常,核左移,当我移动的变量与常数才有效。

Right shift works fine, left shift only works when I'm shifting a variable versus a constant.

任何人都可以证实这一点?

Can anyone confirm this?

我使用Visual微与VS2013。无论使用哪种1.0.x的或同一故障1.5 Arduino的结果编制。

I'm using Visual Micro with VS2013. Compiling with either 1.0.x or 1.5 arduino results in the same failure.

在目标:
A = 0xFFFFFF00
C = 0x0000FF00

On the target: A = 0xFFFFFF00 C = 0x0000FF00

推荐答案

问题是相关的符号/无符号隐式转换。

The problem is related to the signed/unsigned implicit cast.

使用 uint32_t的一个= 0xFF的&LT;&LT; 8; 你的意思


  • 0xFF的声明;它是一个符号字符;

  • 有一个&LT;&LT;操作,使变量转换为int。因为它是一个符号的字符(所以它的价值是-1),它填充为1,preserve的迹象。所以变量 0xFFFFFFFF的;

  • 将移,所以 A = 0xFFFFFF00

  • 0xFF is declared; it is a signed char;
  • There is a << operation, so that variable is converted to int. Since it was a signed char (and so its value was -1) it is padded with 1, to preserve the sign. So the variable is 0xFFFFFFFF;
  • it is shifted, so a = 0xFFFFFF00.

如果您想重现相同的行为,试试这个code:

If you want to reproduce the same behaviour, try this code:

uint32_t a = 0xFF << 8;
uint32_t b = (signed char)0xFF;
uint32_t c = b << 8;

Serial.println(a, HEX);
Serial.println(b, HEX);
Serial.println(c, HEX);

的结果是

FFFFFF00
FFFFFFFF
FFFFFF00

或者,在其他的方式,如果你写

Or, in the other way, if you write

uint32_t a = (unsigned)0xFF << 8;

你得到 A = 0x0000FF00

有只有两个奇怪的事情与编译器:​​

There are just two weird things with the compiler:


  1. uint32_t的一个=(unsigned char型)为0xFF&LT;&LT; 8; 返回= 0xFFFFFF00

  2. uint32_t的一个= 0x000000FF&LT;&LT; 8; 返回= 0xFFFFFF00太

  1. uint32_t a = (unsigned char)0xFF << 8; returns a = 0xFFFFFF00
  2. uint32_t a = 0x000000FF << 8; returns a = 0xFFFFFF00 too.

也许这是一个错误投在编译器......

Maybe it's a wrong cast in the compiler....

这篇关于不按预期工作Arduino的左移,编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆