Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: XOR each character in a string

I'm trying to validate a checksum on a string which in this case is calculated by performing an XOR on each of the individual characters.

Given my test string:

check_against = "GPGLL,5300.97914,N,00259.98174,E,125926,A"

I figured it would be as simple as:

result = 0
for char in check_against:
    result = result ^ ord(char)

I know the result should be 28, however my code gives 40.

I'm not sure what encoding the text is suppose to be in, although I've tried encoding/decoding in utf-8 and ascii, both with the same result.

I implemented this same algorithm in C by simply doing an XOR over the char array with perfect results, so what am I missing?

Edit

So it was a little while ago that I implemented (what I thought) was the same thing in C. I knew it was in an Objective-C project but I thought I had just done it this way. Totally wrong, first there was a step where I converted the checksum string value at the end to hex like so (I'm filling some things in here so that I'm only pasting what is relevant):

 unsigned int checksum = 0;
 NSScanner *scanner = [NSScanner scannerWithString:@"26"];
 [scanner scanHexInt:&checksum];

Then I did the following to compute the checksum:

 NSString sumString = @"GPGLL,5300.97914,N,00259.98174,E,125926,A";
 unsigned int sum = 0;
 for (int i=0;i<sumString.length;i++) {
     sum = sum ^ [sumString characterAtIndex:i];
 }

Then I would just compare like so:

 return sum == checksum;
like image 941
Flynn Avatar asked Sep 06 '26 10:09

Flynn


1 Answers

So as @metatoaster, @XD573, and some others in the comments have helped figure out, the issue was the difference between the result, which was base 10, and my desired solution (in base 16).

The result for the code, 40 is correct - in base 10, however my correct value I was trying to achieve, 28 is given in base 16. Simply converting the solution from base 16 to base 10, for example like so:

int('28', 16)

I get 40, the computed result.

like image 58
Flynn Avatar answered Sep 08 '26 18:09

Flynn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!