Converting hex to binary and displaying which bits are set

조회 수: 10 (최근 30일)
Darren
Darren 2013년 2월 24일
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!
Walter Roberson
Walter Roberson 2013년 2월 27일
str = dec2bin(d,n) produces a binary representation with at least n bits.

댓글을 달려면 로그인하십시오.

카테고리

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