Bitwise XOR on ASCII string

Hey everyone,

I am currently trying to do a simple bitwise XOR on a msg.payload (ASCII string) coming from a serial port. I tried to approach it like I would C programming, but no cigar. Is this even possible in the function block? Any info helps. Thanks.

//Grab Payload to manipulate
var check_sum_string = msg.payload.toString('utf8');
var check_sum;
//Create global flag to raise in order to halt the flow of data
var check_sum_flag = global.get('CS_valid');

for(i=0; i < msg.payload.length; i++){
check_sum = check_sum_string[i] ^ check_sum_string[i+1];
}
msg.payload = check_sum;

if(check_sum !== 0){
check_sum_flag = 1;
global.set('CS_valid',check_sum_flag);
}

return msg;

I am currently using this to validate a checksum, but my output seems to always be 0x00, even if I fudge the input string. Any suggestions?

A few ideas
Are you sure your input is a string and not a buffer object (set of bytes)?

If your sure its a string then I'd change it to a buffer

var check_sum_string = Buffer.from( msg.payload, 'utf8' )

I'd use

var check_sum = 0

to initialise it as numeric

check_sum = check_sum_string[i] ^ check_sum_string[i+1];

looks a bit wrong on the logic front :slight_smile:

I'd try something like

check_sum = check_sum ^ check_sum_string[i]
1 Like

Thanks for that quick response. I modified it using your guide and it works flawlessly. Thanks!