|
| 1 | +function newname = decodevarname(name,varargin) |
| 2 | +% |
| 3 | +% newname = decodevarname(name) |
| 4 | +% |
| 5 | +% Decode a hex-encoded variable name (from encodevarname) and restore |
| 6 | +% its original form |
| 7 | +% |
| 8 | +% This function is sensitive to the default charset |
| 9 | +% settings in MATLAB, please call feature('DefaultCharacterSet','utf8') |
| 10 | +% to set the encoding to UTF-8 before calling this function. |
| 11 | +% |
| 12 | +% author: Qianqian Fang (q.fang <at> neu.edu) |
| 13 | +% |
| 14 | +% input: |
| 15 | +% name: a string output from encodevarname, which converts the leading non-ascii |
| 16 | +% letter into "x0xHH_" and non-ascii letters into "_0xHH_" |
| 17 | +% format, where hex key HH stores the ascii (or Unicode) value |
| 18 | +% of the character. |
| 19 | +% |
| 20 | +% output: |
| 21 | +% newname: the restored original string |
| 22 | +% |
| 23 | +% example: |
| 24 | +% decodevarname('x0x5F_a) % returns _a |
| 25 | +% decodevarname('a_') % returns a_ as it is a valid variable name |
| 26 | +% decodevarname('x0xE58F98__0xE9878F_') % returns '变量' |
| 27 | +% |
| 28 | +% this file is part of EasyH5 Toolbox: https://github.com/fangq/easyh5 |
| 29 | +% |
| 30 | +% License: GPLv3 or 3-clause BSD license, see https://github.com/fangq/easyh5 for details |
| 31 | +% |
| 32 | + |
| 33 | +isunpack=jsonopt('UnpackHex',1,varargin{:}); |
| 34 | +newname=name; |
| 35 | +if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) |
| 36 | + return |
| 37 | +end |
| 38 | +if(isunpack) |
| 39 | + if(exist('native2unicode','builtin')) |
| 40 | + h2u=@hex2unicode; |
| 41 | + newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${h2u($2)}'); |
| 42 | + else |
| 43 | + pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); |
| 44 | + pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); |
| 45 | + if(isempty(pos)) |
| 46 | + return; |
| 47 | + end |
| 48 | + str0=name; |
| 49 | + pos0=[0 pend(:)' length(name)]; |
| 50 | + newname=''; |
| 51 | + for i=1:length(pos) |
| 52 | + newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; |
| 53 | + end |
| 54 | + if(pos(end)~=length(name)) |
| 55 | + newname=[newname str0(pos0(end-1)+1:pos0(end))]; |
| 56 | + end |
| 57 | + end |
| 58 | +end |
| 59 | + |
| 60 | +%-------------------------------------------------------------------------- |
| 61 | +function str=hex2unicode(hexstr) |
| 62 | +val=hex2dec(hexstr); |
| 63 | +id=histc(val,[0 2^8 2^16 2^32 2^64]); |
| 64 | +type={'uint8','uint16','uint32','uint64'}; |
| 65 | +bytes=typecast(cast(val,type{id~=0}),'uint8'); |
| 66 | +str=native2unicode(fliplr(bytes(:,1:find(bytes,1,'last')))); |
0 commit comments