MATLAB: How to access hex values stored in a char in matlab

char

I used DataHash function from MATLAB File Exchange to generate an SHA-256 Hash code for an input plain audio file. But the resultant Hash code was stored in a 'char' data type. How do I retrieve the hex code from it?

Best Answer

The output types of DataHash are: hex, HEX, double, uint8, base64. You could specify the wanted output type at calling DataHash. hex (hexadecimal number as char vector and lowercase characters) is the default. hex, HEX and base64 reply char vectors. Hexadecimal values are represented as char vectors in general. Therefore your question is not clear. Please post the char vector you have and an example of what you want to get.
  • If your string is like: '5b302b7b2099a97ba2a276640a192485', sscanf is faster than hex2dec or hex2num:
num = sscanf(S, '%2x', [1, Inf])
  • If your string is like: '+tJN9yeF89h3jOFNN55XLg'
function Out = base64toHex(In)
P = [65:90, 97:122, 48:57, 43, 47] + 1; % [0:9, a:z, A:Z, +, /]
v8 = [128, 64, 32, 16, 8, 4, 2, 1];
v6 = [32; 16; 8; 4; 2; 1];
Table = zeros(1, 256);
Table(P) = 1:64;
Data = Table(In(:).' + 1) - 1;
X = rem(floor(bsxfun(@rdivide, Data, v6)), 2);
Num = v8 * reshape(X(1:fix(numel(X) / 8) * 8), 8, []);
Out = sprintf('%.2x', Num);
end
This is a simplified version of a base64 decoder only: It does not consider linebreaks and padding characters. Use it for the output of DataHash only.
  • If you want DataHash to reply the byte values, use:
Opt.Format = 'double'; % Or 'uint8': same values, different type