0

I have to perform a XOR operation on the two strings, I got the python implementation of it:

def sxor(s1,s2):    
    return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2)) 

In the above code , we are running the for loop on the strings and we are creating the tuples of it.

string 1: abcdefghijklmn

string 2: 12345

it will create the tuples out of it

[('a','1'),('b','2'),('c','3'),('d','4'),('e','5')]

we have to perform the xor operation on this tuples

chr(ord('a')^ord('1'))  which will result => p    
chr(ord('b')^ord('2'))  which will result => p    
chr(ord('c')^ord('3'))  which will result => p    
chr(ord('d')^ord('4'))  which will result => p    
chr(ord('e')^ord('5'))  which will result => p

I want output as ppppp. I want to implement the same algorithm in angular

I have done this

export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  array1 = [1, 7, 8, 8, 7];
  array2 = ['r', 'u', 'm', 'a', 'n'];
  zip: any;
  ordValue: any;
  value: any;

  ngOnInit(): void {
    this.ordValue = this.ord('r') ^ this.ord('1');
    console.log(this.ordValue);
    this.value = String.fromCharCode(this.ordValue);
    console.log('ASCII ' + this.value);
  }

  ord(str) {
    return str.charCodeAt(0);
  }
}

which is giving the character after XOR

stackblitz Demo : stackblitz

Santhosh
  • 810
  • 2
  • 10
  • 28
  • 1
    `chr` => `String.fromCharCode`, `ord(a)` => `a.charCodeAt(0)`, `zip` => https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function – georg Jun 24 '21 at 11:55
  • 1
    _"I want to implement..."_ - What have you tried so far to solve this on your own? – Andreas Jun 24 '21 at 11:56
  • 1
    _"how to use ord function and chr function..."_ -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Jun 24 '21 at 11:56
  • https://stackoverflow.com/questions/40100096/what-is-equivalent-php-chr-and-ord-functions-in-javascript – Drashti Dobariya Jun 24 '21 at 12:19

1 Answers1

0

You could use the String.fromCodePoint() and the String.charCodeAt() functions. Something like this (I didn't test it):

function sxor (s1, s2){
let str = '';
for (let i = 0; i < Math.min(s1.length, s2.length); ++i)
    str += String.fromCodePoint(s1.charCodeAt(i) ^ s2.charCodeAt(i));
return str;
}
jeremy302
  • 798
  • 6
  • 10