简体   繁体   English

Perl - 2的补码模256 - C ++等价

[英]Perl - 2's complement modulo 256 - C++ equivalent

I'm working with a Perl script to send values from USB to Arduino. 我正在使用Perl脚本将值从USB发送到Arduino。 Part of the script is a checksum-to-error check of the values in the protocol. 脚本的一部分是对协议中的值进行校验和错误检查。

I would now like to send the data from one Arduino to another, so I need to write the equivalent line in C++. 我现在想将数据从一个Arduino发送到另一个,所以我需要用C ++编写等效的行。

$checksum = ((($val1 + $val2 + $val3 + $val4 + $val5)^255 )+1) & 255;

It is the 2's complement of the sum of the values 1 to 5 modulo 256. 它是1到5模256的总和的2的补码。

How could I write this in C++ for Arduino? 我怎么能用C ++为Arduino写这个?

摆脱美元:

checksum = (((val1 + val2 + val3 + val4 + val5)^255 )+1) & 255;

It would be pretty much the same in C++: 它在C ++中几乎是一样的:

checksum = (((val1 + val2 + val3 + val4 + val5) ^ 255) + 1) & 255;

although you could express this more simply as: 虽然你可以更简单地表达这个:

checksum = -(val1 + val2 + val3 + val4 + val5) & 255;

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

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