1

I want to concatenate last four bits of binary into a number i have tried the following code

x8=magic(4)
x8_n=dec2bin(x8)
m=x8_n-'0'

which gives me the following output m =

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

now i want to take every last 4 bits it each row and convert it into an integer

0

2 Answers 2

3
n = 4; %// number of bits you want
result = m(:,end-n+1:end) * pow2(n-1:-1:0).'; %'// matrix multiplication

Anyway, it would be easier to use mod on x8 directly, without the intermediate step of m:

result = mod(x8(:), 2^n);

In your example:

result =
     0
     5
     9
     4
     2
    11
     7
    14
     3
    10
     6
    15
    13
     8
    12
     1
1
  • +1 for a complete answer BTW :) OP won't need all those three lines to get to m
    – Divakar
    Mar 31, 2014 at 16:28
2

This could be another approach -

n = 4; %%// number of bits you want
out = bin2dec(num2str(m(:,end-n+1:end)))

Output -

out =

     0
     5
     9
     4
     2
    11
     7
    14
     3
    10
     6
    15
    13
     8
    12
     1
3
  • 1
    Or, more simply, out = bin2dec(x8_n(:,end-n+1:end)) :-) +1
    – Luis Mendo
    Mar 31, 2014 at 16:21
  • what if i want to take the middle two bits of the m array ?
    – johnny
    Mar 31, 2014 at 17:32
  • 1
    This must work for that case - out = bin2dec(num2str(m(:,3:4))). It's all about manipulating the second index of m, which denotes the column number(s).
    – Divakar
    Mar 31, 2014 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.