Sepideh Abadpour
Sepideh Abadpour

Reputation: 2598

How to get bits of an 8-bit binary column array into separate columns or separate arrays?

Consider the following array:

>> a=[26;94;32];
>> b=dec2bin(a,8);
>> c=str2num(b);
>> d1=bitget(c,1);
>> d2=bitget(c,2);
>> d3=bitget(c,3);
>> d4=bitget(c,4);
>> d5=bitget(c,5);
>> d6=bitget(c,6);
>> d7=bitget(c,7);
>> d8=bitget(c,8);
>> e1=bitget(a,1);
>> e2=bitget(a,2);
>> e3=bitget(a,3);
>> e4=bitget(a,4);
>> e5=bitget(a,5);
>> e6=bitget(a,6);
>> e7=bitget(a,7);
>> e8=bitget(a,8);  

I expect these results from the code:

d1 = e1  
d2 = e2
d3 = e3  
d4 = e4
d5 = e5
d6 = e6
d7 = e7
d8 = e8  

But actually we have the results:

d1 = e1  
d2 = e2
d3 = e3  
d4 != e4
d5 != e5
d6 != e6
d7 != e7
d8 != e8  

Could you please tell me why?

In fact I want to separately write bits of b or c in different columns of an array or in different column arrays and the use it in bitplane slicing.
I don't want to use bitget directly ( It's a homework assignment of my image processing class and the professor has emphasized on not using matlab image processing functions directly). Could you please tell me how can I do that without slowing down the code?

Upvotes: 1

Views: 365

Answers (2)

Robert Seifert
Robert Seifert

Reputation: 25232

There are basically to possibilities to do what you want.

The first mentioned by Divakar:

b = dec2bin(a,8)
c = b-'0'

will return:

c =

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

But this is not how Matlab internally works with bit arrays, instead it assumes a "mirrored" orientation of bits.

To achieve that you could just use de2bi:

c = de2bi(a,8)

which will give you:

c =

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

These arrays are now suitable for the function bitget, which also works with this "mirrored" orientation. That is why you got wrong results.

So for the second solution the comparison works fine:

d6 = c(:,6)
e6 = bitget(a,6)

d6 =

     0
     1
     0


e6 =

     0
     1
     0

Unfortunately de2bi requires the Communications System toolbox, if you don't have it you need to adjust Divakars solution to:

b = dec2bin(a,8)
c = fliplr(b-'0')

Final comparison:

e = [ bitget(a,1),bitget(a,2),bitget(a,3),bitget(a,4), ...    
      bitget(a,5),bitget(a,6),bitget(a,7),bitget(a,8) ]
comp = all( c == e ,3 )

comp =

     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1

Upvotes: 1

Divakar
Divakar

Reputation: 221514

Bits of b into a double array? Try this -

c = b-'0'

Upvotes: 1

Related Questions