Reputation: 340
I have a 32 bit number (uint32) that contains four numbers in the following manner:
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 ?
Upvotes: 4
Views: 167
Reputation: 112769
This can be done with
floor
to get rid of the unwanted rightmost bits, and thenmod
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);
Upvotes: 5