how to convert signed decimal to binary

조회 수: 1 (최근 30일)
saurabh shukla
saurabh shukla 2016년 8월 27일
댓글: saurabh shukla 2016년 8월 28일
i am converting signed decimal to binary reading value from file and after converting writing binary value in to file.here is my code but it gives me wrong answer
%
fid = fopen('dec_bin.txt','r');
fid1=fopen('dec_bin_con.txt','w');
tline = fgetl(fid);
while ischar(tline)
disp(tline);
abstline=abs(tline);
if abstline==tline
out_1a=dec2bin(tline,8);
else
out_1a=dec2bin(tline+256,8);
end;
disp(out_1a);
fprintf(fid1,'%s \n',out_1a);
fprintf(fid1,'\n');
tline = fgetl(fid);
end
fclose(fid);
fclose(fid1);
this is my dec_bin file:
0
-1
1
-2
2
-3
3
-4
4
and my output is:
00110000
0000110110100011
00110001
0000110110100110
00110010
0000110110100111
00110011
0000110110110010
00110100

채택된 답변

Walter Roberson
Walter Roberson 2016년 8월 27일
fgetl() returns a string. You are doing conversion on the characters . If you want to do conversion on the values represented by those characters, you need to convert the strings to numeric form, such as with str2double()
  댓글 수: 1
saurabh shukla
saurabh shukla 2016년 8월 28일
thank you ,now i am getting right output.

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

추가 답변 (0개)

카테고리

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