How to convert binary elements of a cell into decimal number
Show older comments
Hello, I have a cell of binary elements with 0's and 1's of size 1*1624..now i have to convert every 8 binary elements from 1624 elements into a decimal number and store in an array..so,the final output must be of size 1*203(each element in 203 must consists of the value of each 8 binary elements...can anyone help me please
1 Comment
Stephen23
on 8 Feb 2017
Accepted Answer
More Answers (3)
Thibaut Jacqmin
on 8 Feb 2017
Edited: Thibaut Jacqmin
on 8 Feb 2017
Here I create a cell of size 16 (and not 1624) as an example
a = {1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1};
Reshape the cell in a 8xN cell (N = 203 in your case)
a = reshape(a, [8, length(a)/8]);
Convert each column of 8 binary in a decimal number and store it in res
res = [];
for i = 1:size(a, 2)
res(end+1) = bi2de([a{:, i}]);
end
5 Comments
Jyothi Alugolu
on 8 Feb 2017
Jyothi Alugolu
on 8 Feb 2017
Thibaut Jacqmin
on 8 Feb 2017
You can assign it to a new variable if you want/need. I did that because it uses less memory than creating a new variable. You can name it 'b' if you want. Then you will have to replace 'a' by 'b' eveywhere in the following code lines.
Thibaut Jacqmin
on 8 Feb 2017
You don't have to write 203 in the for loop. Indeed size(a, 2) already equals to 203 after reshaping.
Jyothi Alugolu
on 10 Feb 2017
Alexandra Harkai
on 8 Feb 2017
Considering it's a 1*1624 numeric array you have in the cell A, you can utilise bin2dec to do it after converting the numeric values to a string representation with num2str:
{bin2dec(num2str(reshape(A{:}, 8, size(A{:},2)/8)'))}'
1 Comment
Jyothi Alugolu
on 8 Feb 2017
Question: Why is the data in a cell array when a normal matrix would work just as well and make the code simpler? That is instead of:
binaryvector = {1, 0, 0, 1, 0, 1, 1, ...};
Have
binaryvector = [1, 0, 0, 1, 0, 1, 1, ...];
You also haven't told us which bit (1st or 8th) is the LSB and MSB.
Anyway, another way, probably the fastest, to convert your array:
binaryvector = num2cell(randi([0 1], 1, 1624)); %create a cell array of random bits for demonstration only. Use your own data
binaryvector = cell2mat(binaryvector); %convert cell array into matrix as cell array is pointless and just makes manipulating the bits harder
%in version R2016b ONLY:
decimalvector = sum(2.^(7:-1:0)' .* reshape(binaryvector, 8, []));
%in version prior to R2016b:
decimalvector = sum(bsxfun(@times, 2.^(7:-1:0)', reshape(binaryvector, 8, [])));
The above assumes the LSB is the 8th bit, if it's the first bit replace the 7:-1:0 by 0:7
1 Comment
Jan
on 8 Feb 2017
You can omit the sum(), when you use a matrix multiplication.
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!