How to extract the 4 MSBs of decimal numbers in a matrix?

2 Ansichten (letzte 30 Tage)
Mehmet
Mehmet am 23 Mär. 2022
Beantwortet: David Hill am 23 Mär. 2022
Hello everyone,
I would like to know if there is an elegant and easy way to get the 4 MSBs (or 4 LSBs) of decimal numbers in a 2D matrix?
Let's assume that all decimals in the matrix can be represented by 8-bit binary numbers. ([0-255])
I know i can use bitget() function to get the highest 4 bits (4 MSBs) by scanning all elements in the matrix.
For example:
A=[103 12; 250 125];
for i=1:4
bitget(A(i),8:-1:5)
end
A simple code like above can be used to find the highest four bits of all elements in matrix A. However, im just wondering if there is another more efficient method.
Maybe converting A into a binary matrix and then getting the highest 4 bits can be a solution. But Im not quite sure how to do it in an efficient manner.
reshape( dec2bin(A',8)'-'0', [], size(A,1))';
%% how to get the 4 MSBs (or LSBs)?
Thanks,

Akzeptierte Antwort

David Hill
David Hill am 23 Mär. 2022
a=randi(255,10);
d=dec2bin(a(:),8);
msb4=d(:,1:4)-'0';

Weitere Antworten (0)

Kategorien

Mehr zu Networks finden Sie in Help Center und File Exchange

Produkte


Version

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by