This example shows how to convert decimals to binary numbers in their base-2 equivalents.
d_array = [1 2 3 4];
Convert the decimal array to binary by using the de2bi function. Specify that the most significant digit is the leftmost element and set the number of desired columns to 5. The output becomes a 4-by-5 matrix where each row corresponds to a decimal value from the input. Because the largest decimal value in d_array can be expressed in 3 columns, the de2bi pads the matrix with two extra zero columns at the specified most-significant bit side. If you specify too few columns, the conversion will fail.
b_array = de2bi(d_array,5,'left-msb')
b_array = 4×5
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1
0 0 1 0 0
b_array = de2bi(d_array,5,'right-msb')
b_array = 4×5
1 0 0 0 0
0 1 0 0 0
1 1 0 0 0
0 0 1 0 0
If you do not specify a number of columns, the number of columns is exactly what is needed to express the largest decimal of the input.
b_array = de2bi(d_array,'left-msb')
b_array = 4×3
0 0 1
0 1 0
0 1 1
1 0 0
The output rows for specifying a leftmost-significant bit correspond to:
1=0(22)+0(21)+1(20)
2=0(22)+1(21)+0(20)
3=0(22)+1(21)+1(20)
4=1(22)+0(21)+0(20)
b_array = de2bi(d_array,'right-msb')
b_array = 4×3
1 0 0
0 1 0
1 1 0
0 0 1
The output rows for specifying a rightmost-significant bit correspond to:
1=1(20)+0(21)+0(22)
2=0(20)+1(21)+0(22)
3=1(20)+1(21)+0(22)
4=0(20)+0(21)+1(22)