quickest way to convert hex to a 16 bit signed integer
    36 次查看(过去 30 天)
  
       显示 更早的评论
    
looking for the quickest way to convert 16 bit hex into a singed 16 bit int
performance is key here. 
I was doing it with a type cast before but appears very slow
Anyone have any ideas?
1 个评论
  James Tursa
      
      
 2021-7-29
				Please provide details of exact input and desired output.  Is the hex in a char array?  What size?  What is the exact code you have tried so far?
采纳的回答
  Walter Roberson
      
      
 2021-7-29
        
      编辑:Walter Roberson
      
      
 2021-7-31
  
      format long g
N = 100000;
HC = ['0':'9', 'A':'F'];
data = HC(randi(16, N, 4));
timeit(@() typecast(uint16(hex2dec(data)),'int16'), 0)
timeit(@() typecast(uint16(sscanf(data.', '%4x')),'int16'), 0)
timeit(@() typecast(cell2mat(textscan(strjoin(cellstr(data),'\n'),'%xu16')),'int16'), 0)
timeit(@() cell2mat(textscan(strjoin(cellstr(data),'\n'),'%xs16')), 0)
timeit(@() via_ismember_typecast(data, HC), 0)
timeit(@() via_ismember_no_typecast(data, HC), 0)
timeit(@() via_math_typecast(data, HC), 0)
timeit(@() via_discretize_typecast(data, HC), 0)
timeit(@() via_lookup_typecast(data,HC), 0)
function num = via_ismember_no_typecast(data, HC)
   [~, dec] = ismember(data, HC);
   num = dec(:,1)*4096 + dec(:,2)*256 + dec(:,3) * 16 + dec(:,4);
   mask = num > 32767;
   num(mask) = num(mask) - 65536;
   num = int16(num);
end
function num = via_ismember_typecast(data, HC)
   [~, dec] = ismember(data, HC);
   dec = dec-1;   %bin numbers start with 1
   num = typecast(uint16(dec(:,1)*4096 + dec(:,2)*256 + dec(:,3) * 16 + dec(:,4)),'int16');
end
function num = via_math_typecast(data, HC)
   dec = data - '0';
   mask = dec>9;
   dec(mask) = dec(mask) - 7;
   num = typecast(uint16(dec(:,1)*4096 + dec(:,2)*256 + dec(:,3) * 16 + dec(:,4)),'int16');
end
function num = via_discretize_typecast(data, HC)
  dec = discretize(double(data), double(HC)) - 1;  %bin numbers start with 1
  num = typecast(uint16(dec(:,1)*4096 + dec(:,2)*256 + dec(:,3) * 16 + dec(:,4)),'int16');
end
function num = via_lookup_typecast(data, HC)
   lookup(HC) = 0:15;
   dec = lookup(data);
   num = typecast(uint16(dec(:,1)*4096 + dec(:,2)*256 + dec(:,3) * 16 + dec(:,4)),'int16');
end
So via_lookup_typecast is the fastest of these, and via_ismember_typecast is second fastest out of all of these possibilities.
If you are doing a lot of these conversions, then the lookup table can be precomputed -- and it is easy to extend the lookup table to handle lowercase as well as upper case.
6 个评论
  Walter Roberson
      
      
 2021-8-6
				To clarify the chars represent hex, so even though two chars takes 4 bytes of storage, two char is encoding one byte.
更多回答(0 个)
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



