Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
get position of "1" in a binary number

Subject: get position of "1" in a binary number

From: Camille Couzi

Date: 17 Feb, 2011 16:40:06

Message: 1 of 5

Hi!
I am working with binary numbers that have at maximum 8 bits.
I would like to get the position of the ones in my binary numbers, for example:
a=1010;
I will get pos=[4,2]

b=110001
I will get pos=[6,5,1]

Is that possible?
Thakns in advance

Camille.

Subject: get position of "1" in a binary number

From: Nathan

Date: 17 Feb, 2011 16:45:49

Message: 2 of 5

On Feb 17, 8:40 am, "Camille Couzi" <camilleco...@yahoo.fr> wrote:
> Hi!
> I am working with binary numbers that have at maximum 8 bits.
> I would like to get the position of the ones in my binary numbers, for example:
> a=1010;
> I will get pos=[4,2]
>
> b=110001
> I will get pos=[6,5,1]
>
> Is that possible?
> Thakns in advance
>
> Camille.

If b is a string:

b = "10110100"
find(b=='1')
ans =
     1 3 4 6

Otherwise:
b = 10110100
find(num2str(b)=='1')
ans =
     1 3 4 6

I hope that helps.

-Nathan

Subject: get position of "1" in a binary number

From: Camille Couzi

Date: 17 Feb, 2011 17:15:05

Message: 3 of 5

Thanks a lot nathan, that's just what I needed!
Camille!

Subject: get position of "1" in a binary number

From: Husam Aldahiyat

Date: 17 Feb, 2011 17:22:07

Message: 4 of 5

>> a = [1,0,0,1,1];
>> find(a)

ans =

     1 4 5

>>
>> a = '10011';
>> strfind(a,'1')

ans =

     1 4 5

>> a = 19;
>> strfind(dec2bin(a),'1')

ans =

     1 4 5

Subject: get position of "1" in a binary number

From: reza

Date: 17 Feb, 2011 18:02:00

Message: 5 of 5

On Feb 17, 11:40 am, "Camille Couzi" <camilleco...@yahoo.fr> wrote:
> Hi!
> I am working with binary numbers that have at maximum 8 bits.
> I would like to get the position of the ones in my binary numbers, for example:
> a=1010;
> I will get pos=[4,2]
>
> b=110001
> I will get pos=[6,5,1]
>
> Is that possible?
> Thakns in advance
>
> Camille.

And just to introduced one more way:


>> find(de2bi(10110100 ,[], 10, 'left-msb'))

ans =

     1 3 4 6

/reza

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us