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

조회 수: 6 (최근 30일)
Daniel
Daniel 2023년 1월 11일
편집: DGM 2023년 1월 11일
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
Jan
Jan 2023년 1월 11일
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 2023년 1월 11일
편집: DGM 2023년 1월 11일
@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.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by