【问题标题】:How to convert 4 byes to unsigned long variable?如何将 4 个字节转换为无符号长变量?
【发布时间】:2013-07-15 19:25:54
【问题描述】:

如何正确地将 4 个字节转换为一个无符号长变量?

我正在 MPLAB C18 上编程 PIC18,这是我的代码。

unsigned long theseconds = 0x00;
BYTE timeToSave[4];

timeToSave[0] = 0xFF;
timeToSave[1] = 0xFF;
timeToSave[2] = 0x01;
timeToSave[3] = 0x01;

theseconds  =   timeToSave[0] & 0xFF;
theseconds |=  (timeToSave[1] << 8) & 0xFFFF;
theseconds |=  (timeToSave[2] << 16) & 0xFFFFFF;
theseconds |=  (timeToSave[3] << 24) & 0xFFFFFFFF;
printf("\r\nSeconds:%lu",theseconds);

这是我不断得到的输出,Seconds:255

谢谢!

【问题讨论】:

  • 只是跳过面具,你不应该需要它们。如果您正在阅读的缓冲区是小端,其余的似乎都可以。
  • @everclear 是否正常取决于int 的大小。只有sizeof(int)==sizeof(long) 才有效
  • @jeb 是的,看到了,刚从图片网站回来;-)
  • @everclear 我感谢您的努力

标签: c embedded microcontroller pic mplab


【解决方案1】:

这应该可行

unsigned long theseconds = 0x00;
BYTE timeToSave[4];

timeToSave[0] = 0xFF;
timeToSave[1] = 0xFF;
timeToSave[2] = 0x01;
timeToSave[3] = 0x01;

theseconds  =   timeToSave[3];
theseconds  <<= 8;
theseconds  |=   timeToSave[2];
theseconds  <<= 8;
theseconds  |=   timeToSave[1];
theseconds  <<= 8;
theseconds  |=   timeToSave[0];
printf("\r\nSeconds:%lu",theseconds);

您的代码失败有两个原因。
我想int 是 16 位,因此 16 或 24 的移位将导致 0,因为 ANSI-C 中的规则是 timeToSave[x]BYTE(实际上是一个无符号字符)应该扩展为诠释。
显然,一个 16 位的值移位 15 次以上也会导致为 0。

但是为什么你得到 255 而不是 65535?
我想编译器不符合 ANSI,并且不会以适当的方式扩展您的 unsigned char。

要使您的代码正常工作,对每一行进行强制转换就足够了。

theseconds  =   timeToSave[0];
theseconds |=  ((unsigned long)timeToSave[1] << 8);
theseconds |=  ((unsigned long)timeToSave[2] << 16);
theseconds |=  ((unsigned long)timeToSave[3] << 24);

&amp; 掩码是无意义的,因为该值不能超出范围

【讨论】:

  • 它仍然给我 255 作为我的输出
  • 抱歉,我忘记了等号前的|字符
  • @jeb 默认情况下 MPLAB C18 不执行整数提升
  • @ouah 这就是它不符合 ANSI 的原因
  • @jeb option -Oi 必须在 C18 上启用才能在整数提升方面具有符合 ANSI 的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
相关资源
最近更新 更多