1

Currently in matlab i have int array a=[8 3 2 1]; i want to convert it to binary array with four bits each.

for the above int array i would get the following binary array a binary=[1000 0011 0010 0001];

I tried the code given below:

binary = dec2bin([8 3 2 1],4)

I got answer as :

1000
0011
0010
0001

It is a column matrix. But I need a row matrix. [1000 0011 0010 0001]

can anyone help me????

thanks in advance.

1 Answer 1

2

If you don't need the leading zeros, you can use:

binary = str2num(dec2bin([8 3 2 1],4))'

This will give you:

binary =

        1000          11          10           1

If you want the leading zeros, you can use:

binary = cellstr(dec2bin([8 3 2 1],4))'

This will give you:

binary = 

    '1000'    '0011'    '0010'    '0001'

Edit: To take the complement of each bit of the array, you can use:

cmp = cellstr(dec2bin(bitcmp([8 3 2 1],4),4))'

You will get:

cmp = 

    '0111'    '1100'    '1101'    '1110'
Sign up to request clarification or add additional context in comments.

2 Comments

@lara As in method #1, you can get the binary number without leading zeros.
But i need that leading zeros because i need to take the complement of each bit in a number.That is, if it is 0011 , then it changes to 1100.So i need 4 bit representation.

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.