help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Convert a number to its binary representation (not string) as 1D Vec


From: Benjamin Lindner
Subject: Re: Convert a number to its binary representation (not string) as 1D Vector
Date: Mon, 02 Oct 2006 13:47:02 +0200

> Hello there,
> I have a nice function Im writing, for which a hard part for me
> is to convert a number to its binary representation as 1D Vector
> of 1's & 0's. Now Im doing this using a while loop and appending
> to the vector, which seems to throw speed into the trashcan; 
> any and all suggestions welcome.
> 
> Thanks in advance,
> -Muthu

you need to either loop over the number of bits of over the elements 
in your input vector. At least I have not come across a matrix-capable
bitand() implementation. 

doing the operation in one step for all the bits can be done as follows

a = 25;  % number to convert
Nbits =16; % # of bits you want your representation
bitmask = uint32( 2.^[0:Nbits-1]); % create a bitwise-and mask for every bit
a_bw = zeros( length(a), Nbits );
for ii=1:length(a)
  a_bw(ii,:) = bitand( a(ii), bitmap )~=0;
end

this gives

a_bw =

  1  0  0  1  1  0  0  0  0  0  0  0  0  0  0  0

If the number of elements in your vector is large compared to 
the number of bits, it is faster to loop over the number of bits
i.e.

for ii=1:Nbits
   a_bw(:,ii) = bitand( a, bitmask(ii) );
end

this ansatz has some flaws, one of which is the usage of uint32() which
limits to 32 bits...

Both steps, however, require a loop, so this might not be the
solution you asked for...

ben
-- 
Der GMX SmartSurfer hilft bis zu 70% Ihrer Onlinekosten zu sparen! 
Ideal für Modem und ISDN: http://www.gmx.net/de/go/smartsurfer


reply via email to

[Prev in Thread] Current Thread [Next in Thread]