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
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for a complete answer BTW :) OP won't need all those three lines to get to m
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 Comments

Or, more simply, out = bin2dec(x8_n(:,end-n+1:end)) :-) +1
what if i want to take the middle two bits of the m array ?
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).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.