Not able to write the binary data into the text file
1 view (last 30 days)
Show older comments
clc
clear all
close all;
student_id=66438;
a=dec2bin('student_id',16)
studID = fopen('D:\stid.txt','wb');
fprintf(studID,a);
0 Comments
Answers (2)
Jan
on 1 Aug 2015
Edited: Jan
on 1 Aug 2015
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 Comments
Tai Doan
on 20 May 2016
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
on 20 May 2016
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
on 1 Aug 2015
student_id=66438;
a=dec2bin(student_id,16)
studID = fopen('D:\stid.txt','wb');
fprintf(studID,'%s',a)
fclose(studID)
0 Comments
See Also
Categories
Find more on String Parsing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!