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!
0 个评论
回答(1 个)
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 个评论
Walter Roberson
2013-2-27
str = dec2bin(d,n) produces a binary representation with at least n bits.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!