Not able to write the binary data into the text file
이전 댓글 표시
clc
clear all
close all;
student_id=66438;
a=dec2bin('student_id',16)
studID = fopen('D:\stid.txt','wb');
fprintf(studID,a);
답변 (2개)
What is the wanted binary format? dec2bin creates a string, a vector of the type char, which contains the characters '1' and '0'. This is called "binary", but of course it is still a string instead.
This line will not do, what you want:
a = dec2bin('student_id',16)
It converts the characters of the string 'student_id' to a numerical value of the ASCII-codes at first: 's'=115, 't'=116 etc. Then the values are converted to the binary strings. This is not useful.
I guess that you want fwrite instead of fprintf:
student_id=66438;
studID = fopen('D:\stid.txt', 'w'); % There is no 'b', see "doc fopen"
if studID == -1, error('Cannot open file for writing'); end
fwrite(studID, student_id, 'double');
fclose(studID);
Perhaps you want 'uint32' instead of 'double'. So please check your needs.
댓글 수: 2
Tai Doan
2016년 5월 20일
I think, if the number is converted into string, each character will consume 1 byte, while a binary number should only 1 bit. Is there any solution to write exactly binary characters into a file? (1 bit each character?
Guillaume
2016년 5월 20일
Please start your own question rather than hijacking somebody's else.
A character saved into a text file may use 1 byte. It may also use 2, 3, 4 (and maybe more?) depending on the character encoding used for the file.
I have no idea what you mean by 1 bit per character. A bit can only have two values which is not enough to represent characters. The simplest common character encoding, ASCII, requires seven bits.
Azzi Abdelmalek
2015년 8월 1일
student_id=66438;
a=dec2bin(student_id,16)
studID = fopen('D:\stid.txt','wb');
fprintf(studID,'%s',a)
fclose(studID)
카테고리
도움말 센터 및 File Exchange에서 String에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!