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!