converting binary to hexadecimal

7 Ansichten (letzte 30 Tage)
Meghashree G
Meghashree G am 29 Sep. 2015
Bearbeitet: Thorsten am 29 Sep. 2015
bin_str = input('Enter binary number: ', 's');
i = length(bin_str);
disp(i);
n = ceil(i/4);
disp(n);
for g = n : -1 : 1
if i > 4
hex_str(g) = b2h(bin_str(i-3 : i));
i = i - 4;
else
hex_str(g) = b2h(bin_str(1 : i));
end
end
function h = b2h(b)
switch b
case {'0', '00', '000', '0000'}
h = '0';
case {'1', '01', '001', '0001'}
h = '1';
case {'10', '010', '0010'}
h = '2';
case {'11', '011', '0011'}
h = '3';
case {'100', '0100'}
h = '4';
case {'101', '0101'}
h = '5';
case {'110', '0110'}
h = '6';
case {'111', '0111'}
h = '7';
case '1000'
h = '8';
case '1001'
h = '9';
case '1010'
h = 'A';
case '1011'
h = 'B';
case '1100'
h = 'C';
case '1101'
h = 'D';
case '1110'
h = 'E';
case '1111'
h = 'F';
end
I am trying to take the binary input and convert it into hexadecimal value,but im getting the following error:
??? Error: File: filename.m Line: 19 Column: 1 Function definitions are not permitted in this context
I can't understand this error.. What changes should i need to make in order to get the correct output?
Pls help me! Thank you

Akzeptierte Antwort

Thorsten
Thorsten am 29 Sep. 2015
Bearbeitet: Thorsten am 29 Sep. 2015
You have a script and try to define a function in line 19. This is not allowed. You have to either define b2h in a different file or turn your script into a function.
BTW, is there a particular reason why you do not use
dec2base(bin2dec(bin_str), 16)
  3 Kommentare
Thorsten
Thorsten am 29 Sep. 2015
Bearbeitet: Thorsten am 29 Sep. 2015
You have to convert it do a string using
char(decode1+double('0'))
You can also use dec2hex, as Andrei points out. So you complete code will become
bin_hex = dec2hex(bin2dec(char(decode1+double('0'))));
Meghashree G
Meghashree G am 29 Sep. 2015
Thank you so much :) It helped me a lot...:) Thanks much :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Andrei Bobrov
Andrei Bobrov am 29 Sep. 2015
b = {'1100100101111111101';'1100000011001'};
out = dec2hex(bin2dec(b));

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