Converting hex to binary and displaying which bits are set

9 Ansichten (letzte 30 Tage)
Darren
Darren am 24 Feb. 2013
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!

Antworten (1)

Walter Roberson
Walter Roberson am 24 Feb. 2013
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 Kommentare
Darren
Darren am 27 Feb. 2013
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 am 27 Feb. 2013
str = dec2bin(d,n) produces a binary representation with at least n bits.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by