本文介绍了命令来垫零到二进制数的具体位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要垫零到二进制数的特定位置。循环二进制数阵列的形式,如 DEC2BIN(43)
并添加零和调整大小的声音的车轮的再造。
如何填充零有效地二进制数在Matlab?
循环
位置= [1,3,6];
X = de2bi(43);
XX =翻转(X);KK = 1;
第II = 1:长度(X)+长度(位置)
如果ISEQUAL(职位(KK),XX(二))
%通过一个索引转乘II尾进取,
因为我觉得我的方法不好%留下来了!
X(II)= 0;
位置=位置+ 1;一个现在由于一个填补%持仓量增加
KK = KK + 1;
结束
结束
这感觉太重塑:基本上如何做到Ÿ像xxxxYabcd到xxxx0Yabcd哪里xxxxYabcd是一个二进制数字前得到0
示例
Output
解决方案
Race begins! Mendo wins, gevang is a good second, thewaywewalk is the third and jaheruddin comes in fourth. The Shai's bitshifting is implemented in the shai function, unfortunately not yet getting it run faster.
Results
gevang :2.2e-05
thewaywewalk :5.6975e-05
mendo :2.2102e-05
jaheruddin :0.0001693
shai (poor hhh-implementation) 5.3288e-04
Warmed-up testing of the answers
function test_padding_zeros()
function myOutput=gevang(xx,positions)
nPads = length(positions);
nPadsShifts = 1:nPads;
myOutput = ones(1, length(xx) + nPads); % re-indexing on the new array
myOutput(positions + nPadsShifts) = 0; % padding values
myOutput(myOutput==1) = xx; % set original bit values
end
function myOutput=thewaywewalk(x,positions)
idx = numel(x):-1:1;
myOutput = num2cell(x);
myOutput(2,idx(positions)) = {0};
myOutput = [myOutput{:}];
end
function myOutput=jaheruddin(myInput,positions) % myInput can be a row vector or a matrix!
n = size(myInput,2)+numel(positions);
myOutput = false(size(myInput,1),n);
myOutput(:,setxor((1:length(positions)),1:n))=myInput;
end
function myOutput=mendo(myInput,positions)
myOutput = ones(1,length(myInput)+length(positions));
myOutput(positions+(1:length(positions))) = 0;
myOutput(myOutput==1) = myInput;
end
function out = bizarreBitShift( bNum, fromBit, shiftAmount )
% construct a mask
msk = uint32( (2^( fromBit - 1 ) )-1 );
shiftPart = bitand( uint32(bNum), bitcmp(msk) ); % bitcmp - complement of bits
staticPart = bitand( uint32(bNum), msk );
out = bitshift( shiftPart , shiftAmount );
out = bitor( out, staticPart );
end
function myOutput=shai(myInput,positions)
shiftAmount=1;
myOutput=sprintf('%d',myInput);
myOutput=bin2dec(myOutput);
k=0;
for ii=1:length(positions)
fromBit=positions(ii)+k;
myOutput=bizarreBitShift(myOutput, fromBit, shiftAmount);
k=k+1;
end
myOutput=ismember(dec2bin(myOutput),'1');
end
positions = [1 3 6]; %// example data
myInput = [1 0 1 0 1 1]; %// example data
ggevang=@() gevang(myInput,positions);
tthewaywewalk=@() thewaywewalk(myInput,positions);
mmendo=@() mendo(myInput,positions);
jjaheruddin=@() jaheruddin(myInput,positions);
sshai=@() shai(myInput,positions);
timeit(ggevang)
timeit(tthewaywewalk)
timeit(mmendo)
timeit(jjaheruddin)
timeit(sshai)
end
这篇关于命令来垫零到二进制数的具体位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!