Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

perl

arduino

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?

like image 704
jowan sebastian Avatar asked Jan 19 '26 09:01

jowan sebastian


2 Answers

Just get rid of the dollars:

checksum = (((val1 + val2 + val3 + val4 + val5)^255 )+1) & 255;
like image 90
fredoverflow Avatar answered Jan 20 '26 21:01

fredoverflow


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;
like image 36
Paul R Avatar answered Jan 20 '26 22:01

Paul R