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);

Answers (2)

Jan
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

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?
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.

Sign in to comment.

student_id=66438;
a=dec2bin(student_id,16)
studID = fopen('D:\stid.txt','wb');
fprintf(studID,'%s',a)
fclose(studID)

Tags

Asked:

on 1 Aug 2015

Commented:

on 20 May 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!