Command to pad zeros to specific locations in binary numbers?

后端 未结 5 1498
孤独总比滥情好
孤独总比滥情好 2021-01-07 02:48

I need to pad zeros to specific locations in binary numbers. Looping the array form of a binary number such as dec2bin(43) and adding the zeros and adjusting th

5条回答
  •  暖寄归人
    2021-01-07 03:40

    Shai provided here bitshifting solution for a single binary number. I use it below to pad the zeros, the solution can probably made far faster -- currently being one of the slowest solution (some unnecessary dec2bin) or about the same speed as Jaheruddin's solution.

    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
    
    sshai=@() shai(myInput,positions);
    timeit(sshai)
    

    Timing

    ans =
    
       5.3288e-04
    

提交回复
热议问题