Converting hex to binary and displaying which bits are set

10 次查看(过去 30 天)
Hi, I am currently working on a function that will output what state a system is in at a particular point in time indicated by a hex input. For the purpose of this particular peice of code it is only one byte, however i may require to adapt it to two bytes.
I am looking to be able to enter for e.g. [a b c d e f g h] = flags ('F3') and then see the state for each bit displayed on the screen.
My code i'm working on is:
function [ a b c d e f g h ] = flags( hex_str )
x = dec2bin(hex2dec(hex_str));
if x('bit 0') == 0; % a
disp('not_follow');
else
disp('follow');
if x('bit 1') == 0; % b
disp('not_cleared');
else
disp('cleared');
if x('bit 2') == 0; % c
disp('not_loading');
else
disp('loading');
if x('bit 3') == 0; % d
disp('not_locked');
else
disp('locked');
if x('bit 4') == 0; % e
disp('not_initiated');
else
disp('initiated');
if x('bit 5') == 0; % f
disp('not_open');
else
disp('open');
if x('bit 6') == 0; % g
disp('not_ready');
else
disp('ready');
if x('bit 7') == 0; % h
disp('not_used');
else
disp('used');
end
Could someone tell me where i am going wrong or suggest an easier solution to my problem? Any help is much appreciated. Thanks!

回答(1 个)

Walter Roberson
Walter Roberson 2013-2-24
x will be a vector of values. Index it at a numeric index, not at a string. x(1), x(2), and so on.
Hint: re-read the documentation for dec2bin() and look at the optional parameters.
  4 个评论
Darren
Darren 2013-2-27
Thanks Walter. Can you give me an example of how you would implement that in code? I have been playing about with it for the past 2 days getting nowhere!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by