convert hexadecimal to string

119 views (last 30 days)
Meghashree G
Meghashree G on 29 Sep 2015
Edited: Guillaume on 30 Sep 2015
i have con = 63727970746F,that is hexadecimal code..When converted to string it should give crypto..How to code for this? con will be dynamically generating,so can't take fixed hexadecimal value,should use the variable name in computation..Please help!Thank you

Answers (2)

Thorsten
Thorsten on 29 Sep 2015
hexnum = '63727970746F';
num = hex2dec(hexnum)
  4 Comments
Guillaume
Guillaume on 30 Sep 2015
1. Your code need comments. Particularly as it looks more complicated than it should be
2. bitxor is semantically wrong in the context you're using it. It just happens to give you the correct result because your vectors are just 0 and 1. xor is the correct function to use in this context.
3. char(x + double('0')) is the same as char(x + '0'). The latter is more readable.
4. give better names to your variables, shape1, result, ... don't mean anything to the reader. hex_key would imply a string of hexadecimal character, yet it is a string of binary characters. etc...
From my reading of your code, con is a string, so why doesn't hex2dec work? if you get an error, please give the full text of the error (everything that is shown in red).

Sign in to comment.


Guillaume
Guillaume on 30 Sep 2015
Edited: Guillaume on 30 Sep 2015
As mentioned in my comment, I don't understand why you have a problem with hex2dec. If you want the result as a string representing the decimal value, simply use:
num2str(hex2dec(con))
Note that the code you posted only works if data1 is exactly 24 characters and data5 exactly three numbers, yet you never check that and instead just take whatever number of bytes are available.
In any case, your code can be greatly simplified, never using any conversion to binary or hexadecimal, or strings
%build up demo data:
gattaca = randi([1 4], 1, 24); symbols = 'ATGC';
data1 = symbols(gattaca); %poorly named variable
data5 = randi([0 255], 1, 3); %poorly named variable
%convert data1 to numbers
[~, x] = ismember(data1, 'ATGC');
data1asnumber = sum(bsxfun(@times, reshape(x, 4, []) - 1, [64; 16; 4; 1]));
%perform binary xor on data1 and data5
decode = bitxor(data1asnumber, data5);
%calculate con as hex string (if you really want to)
con = reshape(dec2hex([decode data5])', 1, []);
%get output as decimal string (does not need con)
dec_string = num2str(polyval([decode data5], 256));

Community Treasure Hunt

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

Start Hunting!