Home > Mobile >  What is the fastest method to extract multiple numbers embedded in a 32 bit binary number in Matlab
What is the fastest method to extract multiple numbers embedded in a 32 bit binary number in Matlab

Time:09-17

I have a 32 bit number (uint32) that contains four numbers in the following manner:

  • Var1 is in bits 32:31
  • Var2 is in bits 30:22
  • Var3 is in bits 21:13
  • Var4 is in bits 12:1

The following code works but I'd like to make it faster

Var1=bitshift(fourbytes,-30);
Var2_temp=bitshift(fourbytes,-21);
Var2=bitand(Var2_temp,511);
Var3_temp=bitshift(fourbytes,-12);
Var3=bitand(Var2_temp,511);
Var4=bitand(fourbytes,2^12-1));

Example:

fourbytes = 2149007896;

Results in

Var1=2;
Var2=0;
Var3=372
Var4=536

I've tried something like

Var1=bin2dec(num2str(bitget(fourbytes,32:-1:31)));

but that is incredibly slow as is bi2de

bi2de(bitget(onebyte(1),32:-1:31),'left-msb');

Is my only alternative to write this part in C, or is there a better way I'm missing ?

CodePudding user response:

This can be done with

  • division followed by floor to get rid of the unwanted rightmost bits, and then
  • mod to get rid of the unwanted leftmost bits.

I haven't timed it, but it's probably faster than your current approach.

fourbytes = 2149007896;
var1 = floor(fourbytes/2^30);
var2 = mod(floor(fourbytes/2^21), 2^9);
var3 = mod(floor(fourbytes/2^12), 2^9);
var4 = mod(fourbytes, 2^12);
  • Related