我有一种很奇怪的矛盾。
我正在准备读取关于Arduino的二进制文件(对于midi球员,如果您感兴趣的话)。如果我试图将Arduino上的4个字节组合成一个long,就会给出一个错误的结果。
但是,如果我在PC上使用相同的代码,我将得到正确的值。
输入是: 0x12481248 (0x12,0x48,0x12,0x48) (实际上是一个随机数)。
阿迪诺: 4680。
代码::块表示: 306713160。
4680与0x1248相同,当您在Arduino上使用int而不是long (省略了2个字节)时,会得到相同的结果。
Arduino代码:
void setup(){
Serial.begin(57600);
char read1 = 0x12;
char read2 = 0x48;
char read3 = 0x12;
char read4 = 0x48;
unsigned long testint = read1<<24|read2<<16|read3<<8|read4;
unsigned long testint2 = 306713160;
Serial.println(testint);
Serial.println(testint2);
}
void loop(){}
testint2是为了表明它不是由Serial.println()引起的。串行监视器的输出确实是:
四千六百八十
306713160
C++代码:
#include <iostream>
using namespace std;
int main(){
char read1 = 0x12;
char read2 = 0x48;
char read3 = 0x12;
char read4 = 0x48;
unsigned long testint = read1<<24|read2<<16|read3<<8|read4;
cout << testint;
}
知道怎么回事吗?
另外,有人知道用Arduino/SD库转换字节的更好/更漂亮的方法吗?
发布于 2015-12-06 18:46:21
在Arduino,int
size is 16 bits。
在这一行:
unsigned long testint = read1<<24|read2<<16|read3<<8|read4;
即使结果存储在unsigned long
(32位)中,按位操作也是在int
上进行的。
将此行更改为:
unsigned long testint = (unsigned long)read1 << 24
| (unsigned long)read2 << 16
| (unsigned long)read3 << 8
| (unsigned long)read4;
发布于 2015-12-06 18:45:37
我期望在任何平台上得到结果4680 (=0x1248),而在任何平台上,sizeof(int)=2,我认为这就是arduino的情况。
这是因为(read1 << 24)被隐式转换为int (不太长),所以上两个字节就会丢失。Yout应该首先将读*转换为未签名的long first
发布于 2016-11-16 09:03:10
还可以使用以下代码:
uint8_t data[4];
data[0]=read4;
data[1]=read3;
data[2]=read2;
data[3]=read1;
unsigned long testint =*(unsigned long*)(&data);
https://stackoverflow.com/questions/34121110
复制相似问题