# Bitwise XOR on ASCII string

**URL:** <https://discourse.nodered.org/t/bitwise-xor-on-ascii-string/16552>\
**Category:** General\
**Created:** [10 October 2019 13:30 UTC](https://discourse.nodered.org/t/bitwise-xor-on-ascii-string/16552 "2019-10-10T13:30:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![NTC](https://avatars.discourse-cdn.com/v4/letter/n/77aa72/32.png) [@NTC](https://discourse.nodered.org/u/NTC)\
**Post date:** [10 October 2019 13:30 UTC](https://discourse.nodered.org/t/bitwise-xor-on-ascii-string/16552/1 "2019-10-10T13:30:23Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![cymplecy](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/cymplecy/32/2773_2.png) [@cymplecy](https://discourse.nodered.org/u/cymplecy)\
**Post date:** [10 October 2019 17:01 UTC](https://discourse.nodered.org/t/bitwise-xor-on-ascii-string/16552/2 "2019-10-10T17:01:01Z")

</div>

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

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

```

I'd use

```auto
var check_sum = 0

```

to initialise it as numeric

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

```

looks a bit wrong on the logic front 🙂

I'd try something like

```auto
check_sum = check_sum ^ check_sum_string[i]

```

---

<div class="post-metadata">

**Author:** ![NTC](https://avatars.discourse-cdn.com/v4/letter/n/77aa72/32.png) [@NTC](https://discourse.nodered.org/u/NTC)\
**Post date:** [10 October 2019 19:01 UTC](https://discourse.nodered.org/t/bitwise-xor-on-ascii-string/16552/3 "2019-10-10T19:01:07Z")

</div>

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