convert hexadecimal to string
65 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
Thorsten
2015-9-29
hexnum = '63727970746F';
num = hex2dec(hexnum)
4 个评论
Guillaume
2015-9-30
编辑:Guillaume
2015-9-30
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).
Guillaume
2015-9-30
编辑:Guillaume
2015-9-30
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));
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!