简体   繁体   English

错误的有效载荷转换 Arduino

[英]Wrong payload conversion Arduino

Hello I'm newbie with arduino and maybe is a silly question, but I'm trying to convert long numbers to byte .您好,我是 arduino 的新手,也许是一个愚蠢的问题,但我正在尝试将long数字转换为byte

My code is:我的代码是:

float f_longitud = 179.1234567;
byte payload[4];

long longitud= f_longitud * 10000000;
SerialUSB.println(longitud);

payload[0] = (byte) ((longitud & 0xFF000000) >> 24 );
payload[1] = (byte) ((longitud & 0x00FF0000) >> 16 );
payload[2] = (byte) ((longitud & 0x0000FF00) >> 8 );
payload[3] = (byte) ((longitud & 0X000000FF));
SerialUSB.println(payload[0]);

The problem is that the first println theoretically has to show 1791234567 , because I'm just multiplying 179.1234567 x 10000000 but it shows 1791234560 .问题是第一个println理论上必须显示1791234567 ,因为我只是乘以179.1234567 x 10000000但它显示1791234560 Why is this 0 appearing?为什么会出现这个 0? Where is the 7? 7号在哪里?

The second problem is that payload[0] should be 6A hex, but my println shows 106 .第二个问题是payload[0]应该是6A hex,但我的println显示106 Why is not converting it correctly?为什么转换不正确? Does this problem comes because of the previous error?这个问题是因为之前的错误而出现的吗?

Below I show a scheme of what I'm doing.下面我展示了我正在做的事情。 It's from the this link .它来自这个链接

在此处输入图像描述

Thank you very much!非常感谢!

The problem is that the first println theoretically has to show 1791234567, because I'm just multiplying 179.1234567 x 10000000 but it shows 1791234560. Why is this 0 appearing?问题是第一个 println 理论上必须显示 1791234567,因为我只是乘以 179.1234567 x 10000000 但它显示 1791234560。为什么会出现这个 0? Where is the 7? 7号在哪里?

This is probably due to precision limits of float .这可能是由于float的精度限制。 Try double instead.尝试double

The second problem is that payload[0] should be 6A hex, but my println shows 106.第二个问题是 payload[0] 应该是 6A hex,但是我的 println 显示的是 106。

You can provide a format for println() , like this:您可以为println()提供格式,如下所示:

SerialUSB.println(payload[0], HEX);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM