简体   繁体   中英

Perl - 2's complement modulo 256 - C++ equivalent

I'm working with a Perl script to send values from USB to 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++.

$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.

How could I write this in C++ for Arduino?

摆脱美元:

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

It would be pretty much the same in 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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