How can I make a bit-wise XOR operation and get back the string?

7 vues (au cours des 30 derniers jours)
Daniel
Daniel le 11 Jan 2023
Modifié(e) : DGM le 11 Jan 2023
Assume:
String1 = Dani;
String2 = Dagi;
binary1 = dec2bin(String1);
binary2 = dec2bin(String2);
binary1 = reshape(binary1.',[],1).';
binary2 = reshape(binary2.',[],1).';
Then, How can I XORED binary1 and binary2 and then back change into string? Anyone please help.
Finally what I want is; the XORED result and the string format of XORED result.
  4 commentaires
Jan
Jan le 11 Jan 2023
This operation is not meaningful:
String1 = Dani;
binary1 = dec2bin(String1);
What is Dani? Do you mean 'Dani' or "Dani", such that String1 is a char vector or a string?
What do you expect dec2bin to do then? Matlab stores characters as UINT16 value.
It is easy to perform an XOR with numerical values in Matlab. Converting them to binary strings makes it difficult. So what is the reason for this conversion?
DGM
DGM le 11 Jan 2023
Modifié(e) : DGM le 11 Jan 2023
@Jonas already accomplished what was described. Regardless of whether you choose to cause yourself further problems by needlessly concatenating all the rows, the result is the same.
binary1 = '1000100110000111011101101001';
binary2 = '1000100110000111001111101001';
xored = char((binary1~=binary2)+'0');
xored = reshape(xored,[],4).'
xored = 4×7 char array
'0000000' '0000000' '0001001' '0000000'
xored = bin2dec(xored).'
xored = 1×4
0 0 9 0
char(xored)
ans = ' '
Note that you can't generally presume that the binary words returned by dec2bin() are always the same length when used this way. In this case, they're 7 bits, but they can be up to 16 bits. Consider the example:
s1 = 'C';
s2 = 'Ĉ';
b1 = dec2bin(s1)
b1 = '1000011'
b2 = dec2bin(s2)
b2 = '100001000'
The simple remedy is to explicitly specify how many bits you want when you call dec2bin().
As Jan notes, this can be done without conversion
s1 = 'Dani';
s2 = 'Dagi';
result = bitxor(uint16(s1),uint16(s2)) % in numeric
result = 1×4
0 0 9 0
result = char(result) % in char
result = ' '
Note that this is the same result Jonas gave. Character 0x0009 is a horizontal tab, so it renders differently depending on where it is.

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Numeric Types dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by