converting binary to hexadecimal

조회 수: 8 (최근 30일)
Meghashree G
Meghashree G 2015년 9월 29일
편집: Thorsten 2015년 9월 29일
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

채택된 답변

Thorsten
Thorsten 2015년 9월 29일
편집: Thorsten 2015년 9월 29일
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
Thorsten
Thorsten 2015년 9월 29일
편집: Thorsten 2015년 9월 29일
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 2015년 9월 29일
Thank you so much :) It helped me a lot...:) Thanks much :)

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2015년 9월 29일
b = {'1100100101111111101';'1100000011001'};
out = dec2hex(bin2dec(b));

카테고리

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