Determining which flags are set from a hexadecimal input

Hi,
I'm currently looking into writing a program which reads a hexadecimal input, and then tells me which flags are set depending on what the hex input is.
For e.g. input - hex = 0062
output - 'Byte 0 bit 1 is set' therefore parameter x - 'Byte 1 bit 0 is set' therefore parameter y - 'Byte 1 bit 3 is set' therefore parameter z
Could anyone assist in what the best way would be to program this code?
Thanks

 采纳的回答

function flags = which_bit_set(hex_str)
x = dec2bin(hex2dec('hex_str'));
for i = 1:length(x)
disp(['Bit ' int2str(i)])
if x(length(x) - i + 1) == '0'
disp(' not');
end
disp('set')
end

8 个评论

Thanks Thorsten. How would you get this code to display a different word for each bit rather than every bit saying either set or not set?
i.e. bit 0 says either follow or not follow, bit 1 says either used or not used, bit 2 says ready or not ready etc?
parmname = {'set', 'used', 'ready', ...};
[...]
disp(parmname{i})
Where in the code to i enter those lines? I have tried the following:
function [ flags ] = which_bit_set(hex_str)
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
x = dec2bin(hex2dec(hex_str));
for i = 0:7
disp(['Bit ' int2str(i)])
parmname = ['set', 'used', 'ready', 'past', 'help', 'seen', 'one', 'two'];
if x(7 - i + 1) == '0'
disp(parmname{i});
end
disp('set')
end
However, this keeps producing errors!
function [ flags ] = which_bit_set(hex_str)
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
parmname = {'set', 'used', 'ready', 'past', 'help', 'seen', 'one', 'two'}; %curly brackets!!
x = dec2bin(hex2dec(hex_str));
for i = 0:7
disp(['Bit ' int2str(i)])
if x(7 - i + 1) == '0'
disp('not')
end
disp(parmname{i});
end
that code gives the following error:
Subscript indices must either be real positive integers or logicals.
Error in which_bit_set (line 13) disp(parmname{i});
Thanks Walter that error has fixed however the following error has occured:
Error in which_bit_set (line 4) parmname = {'set', 'used', 'ready', 'past', 'help', 'seen', 'one', 'two'}; %curly brackets!!
Output argument "flags" (and maybe others) not assigned during call to "C:\Documents\MATLAB\which_bit_set.m>which_bit_set".
Adapt:
is_it_on = 'not ';
flags{i+1} = ['Bit ', int2str(i), is_it_on, parmname{i+1}]);

请先登录,再进行评论。

更多回答(1 个)

Perhaps this helps:
Str = '0062';
Num = sscanf(Str, '%.2x'); % Or is it '%2x'? Or HEX2DEC()
for iByte = 1:2
Byte = Num(iByte);
for iBit = 0:7
value = bitget(Byte, iBit);
fprintf('Byte %d Bit %d: %d', iByte, iBit, value);
end
end
This does not hit the "therefore parameter x" part, but I do not understand this expression.

类别

帮助中心File Exchange 中查找有关 Just for fun 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by