ellah Faris
ellah Faris

Reputation: 13

xor between two numbers (after hex to binary conversion)

i donot know why there is error in this coding:

hex_str1 = '5'
bin_str1 = dec2bin(hex2dec(hex_str1))
hex_str2 = '4'
bin_str2 = dec2bin(hex2dec(hex_str2))
c=xor(bin_str1,bin_str2)

the value of c is not correct when i transform the hex to binary by using the xor function.but when i used the array the value of c is correct.the coding is

e=[1 1 1 0];
f=[1 0 1 0];
g=xor(e,f)

what are the mistake in my first coding to xor of hec to binary value??anyone can help me find the solution...

Upvotes: 1

Views: 3447

Answers (2)

Pankaj Pateriya
Pankaj Pateriya

Reputation: 641

it is really helpful, and give me the correct conversion while forming HMAC value in matlab... but in matlab you can not convert string of length more than 52 character using bin2dec() function and similarly hex2dec() can not take hexadecimal character string more than 13 length.

Upvotes: 0

Eitan T
Eitan T

Reputation: 32930

Your mistake is applying xor on two strings instead of actual numerical arrays.

For the xor command, logical "0"s are represented by actual zero elements. Any non-zero elements are interpreted as logical "1"s.

When you apply xor on two strings, the numerical value of each character (element) is its ASCII value. From xor's point of view, the zeroes in your string are not really zeroes, but simply non-zero values (being equal to the ASCII value of the character '0'), which are interpreted as logical "1"s. The bottom line is that in your example you're xor-ing 111b and 111b, and so the result is 0.

The solution is to convert your strings to logical arrays:

num1 = (bin_str1 == '1');
num2 = (bin_str2 == '1');
c = xor(num1, num2);

To convert the result back into a string (of a binary number), use this:

bin_str3 = sprintf('%d', c);

... and to a hexadecimal string, add this:

hex_str3 = dec2hex(bin2dec(bin_str3));

Upvotes: 2

Related Questions