Faster version of dec2bin function for converting many elements?

binary, matlab

Solution

An even faster way is to use lookup tables. Since you know all the values are intensities between 0 and 255, you construct the binary equivalent of each to speed up the process.

% build table (computed once) [using gnovice option#1]
lookupTable = cell2mat(arrayfun(@(i)bitget([0:255]',9-i),1:8,'UniformOutput',0));

% random' image
I = randi(256, [240 320])-1;

% decimal to binary conversion
binI = lookupTable(I(:)+1,:);

On my machine, it took on average 0.0036329 seconds (only the conversion). Note the lookup table has almost no space overhead:

>> whos lookupTable
  Name               Size            Bytes  Class    Attributes
  lookupTable      256x8              2048  uint8 

Problem

I am reading a bitmap file and converting each of the RGB values ranging from 0 to 255 to binary. So a 240 by 320 bitmap will have 230400 RGB values to convert. The original dec2bin function was too slow, so I wrote my own as I know my value will always be between 0 to 255. But going through 230400 values will still take approx. 6sec on my machine, and a single colour bitmap will take about 2.3sec. Is there anyway to speed things up to be under 1sec or even better 0.5sec, as every msec counts for my application? Here is my code: ``` function s = dec2bin_2(input) if input == 255 s = [1;1;1;1;1;1;1;1]; return; end s = [0;0;0;0;0;0;0;0]; if input == 0 return; end if input >= 128 input = input - 128; s(1) = 1; if input == 0 return; end end if input >= 64 input = input - 64; s(2) = 1; if input == 0 return; end end if input >= 32 input = input - 32; s(3) = 1; if input == 0 return; end end if input >= 16 input = input - 16; s(4) = 1; if input == 0 return; end end if input >= 8 input = input - 8; s(5) = 1; if input == 0 return; end end if input >= 4 input = input - 4; s(6) = 1; if input == 0 return; end end if input >= 2 input = input - 2; s(7) = 1; if input == 0 return; else s(8) = 1; end end end ``` I was thinking if I'm not able to do it in MATLAB then maybe I'll do the conversion in C++. Is this advisable? Thanks.

Original source