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

8 次查看(过去 30 天)
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,

采纳的回答

David Hill
David Hill 2022-3-23
a=randi(255,10);
d=dec2bin(a(:),8);
msb4=d(:,1:4)-'0';

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by