Home > front end >  How to convert decimals to these Ascii characters in matlab?
How to convert decimals to these Ascii characters in matlab?

Time:10-01

I have a char with a bunch of decimals in each line from 0 to 63. I'm trying to convert these decimals to the one that represents it in the image below. So 0 should be changed to A, 1 should be changed to B and so on. Anyone know if there are some functions to make this easier in Matlab?

enter image description here

CodePudding user response:

E.g. start with this char string:

S = ['A':'Z','a':'z','0':'9',' ','/']

Then you can use this for mapping back & forth between the numbers and the characters, offsetting the index by 1. E.g.,

c = 'THEstring'
[~,N] = ismember(c,S); % From char string to numbers
x = N-1 % Offset by 1
C = S(x 1) % From numbers back to char string, offset by 1

CodePudding user response:

I wonder if there is some missing context to your question because this looks a lot like base64 encoding. If that is the case, then to implement this properly, groups of three bytes (24 bits) are encoded by four 6-bit Base64 key values. For example, three 8-bit values such as uint8(0:2) are represented as 00000000 00000001 00000010 in binary. These can then be split into four 6-bit values, 000000 000000 000100 000010, which, per your table, results in 'AAEC'.

Luckily, Matlab has built-in functions encode/decode Base64 with matlab.net.base64encode and matlab.net.base64decode. These include padding with '=' for cases where the number of inputs bytes is not divisible by three. My example above can be replicated with:

V = uint8(0:2);
res = matlab.net.base64encode(V)
matlab.net.base64decode(res) % convert result back
  • Related