473,659 Members | 3,553 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Handling binary data in C - questions

Hi
I have the following 2 questions:
1.How to write binary data to a text file in C? I have a number like
10001010110001 say, I need to put it in the text file so that I can see
the corresponding characters when I open the file.

2. How to extract bits from a byte. I think it is using bit operations,
but for example, how would I extract the 2nd most significant bit in a
byte?

Thanks
Bruce

Nov 14 '05 #1
8 2114


Bruce Lee wrote:
Hi
I have the following 2 questions:
1.How to write binary data to a text file in C? I have a number like
10001010110001 say, I need to put it in the text file so that I can see
the corresponding characters when I open the file.

2. How to extract bits from a byte. I think it is using bit operations,
but for example, how would I extract the 2nd most significant bit in a
byte?

Thanks
Bruce


1. mask a bit print a 0 or 1 , shift left and repeat.

2. Mask using and (&)

ex :
if(abyte & 0x04)printf("1" ); // mask bit 2 0x04 = 00000100
else printf("0");

Nov 14 '05 #2
Sorry but I am still new to C and unable to understand you clearly

1. How to print it? fprintf(fileNum ,"%s","write this"); is what I know.
And I guess %s can be %c as well.
But how to print a bit as you said (0 or 1)? What is the command to
print just 0s and 1s to a file?

2. This masks the 3rd bit from the right since 0x04 is 100? Does &-ing
give a boolean result or an int? In this case, what does abyte & 00x4
return?

Thanks for the explanation
Bruce

Nov 14 '05 #3
Bruce Lee wrote:
Sorry but I am still new to C and unable to understand you clearly

1. How to print it? fprintf(fileNum ,"%s","write this"); is what I know.
And I guess %s can be %c as well.
But how to print a bit as you said (0 or 1)? What is the command to
print just 0s and 1s to a file?

2. This masks the 3rd bit from the right since 0x04 is 100? Does &-ing
give a boolean result or an int? In this case, what does abyte & 00x4
return?

Thanks for the explanation
Bruce


try this:

fprintf(stdout, "%c", data & 0x4 ? '1' : '0');

This will print out a '1' if the 3rd bit is on and '0' if not. It will
be printed to your terminal. If you want the result to go to a
different file just substitue your file pointer in place of stdout.
--
Regards,
Stan Milam
=============== =============== =============== =============== =
Charter Member of The Society for Mediocre Guitar Playing on
Expensive Instruments, Ltd.
=============== =============== =============== =============== =
Nov 14 '05 #4

Stan Milam wrote:
Bruce Lee wrote:
Sorry but I am still new to C and unable to understand you clearly

1. How to print it? fprintf(fileNum ,"%s","write this"); is what I know. And I guess %s can be %c as well.
But how to print a bit as you said (0 or 1)? What is the command to
print just 0s and 1s to a file?

2. This masks the 3rd bit from the right since 0x04 is 100? Does &-ing give a boolean result or an int? In this case, what does abyte & 00x4 return?

Thanks for the explanation
Bruce

try this:

fprintf(stdout, "%c", data & 0x4 ? '1' : '0');

This will print out a '1' if the 3rd bit is on and '0' if not. It

will be printed to your terminal. If you want the result to go to a
different file just substitue your file pointer in place of stdout.
--
Regards,
Stan Milam
=============== =============== =============== =============== =
Charter Member of The Society for Mediocre Guitar Playing on
Expensive Instruments, Ltd.
=============== =============== =============== =============== =


Thanks, but data & 0x4 need not necessarily give a 0 or 1 right? I
mean, if data is 11011000 & 0x4, the result would be 0010000
How do I write the bits to a file using fprintf (or anything else)?
If my character is a, its ascii value will be in bits 1100001. I have
this and I need to write it to the file so that the file has the char
'a'.
Could someone please explain this bit extraction and writing?
Thanks
Bruce

Nov 14 '05 #5
maybe you don't need bit operations.plea se look at the simple code
fragment:
void main()
{
FILE *fp;
fp = fopen("d:\\a.tx t","w+");
printf("---------------\n");
if(fp==NULL)
{
printf("fail to open file \n");
return;
}
fprintf(fp,"%c" ,'a');
fclose(fp);

return;
}
the program is complied in TC20,it only do create a file "a.txt" on
d:\.The content of a.txt
is 'a'.

Nov 14 '05 #6
GrandElf wrote:

maybe you don't need bit operations.plea se look at the simple code
fragment:
1
void main()
2, 3
{
FILE *fp;
4
fp = fopen("d:\\a.tx t","w+");
5
printf("---------------\n");
if(fp==NULL)
{
printf("fail to open file \n");
6
return;
7
}
fprintf(fp,"%c" ,'a');
8
fclose(fp);

return;
9
}


A: Do some research, to find out why your code is broken (the numbers
should give you a few hints as to where the problems are).

B: Fix those problems.

C: Try re-posting if you wish. Of course, the OP might have got bored
of waiting by then.
Nov 14 '05 #7
"GrandElf" <Ni*******@gmai l.com> wrote:
maybe you don't need bit operations.plea se look at the simple code
fragment:
void main()
{
FILE *fp;
fp = fopen("d:\\a.tx t","w+");
printf("---------------\n");
if(fp==NULL)
{
printf("fail to open file \n");
return;
}
fprintf(fp,"%c" ,'a');
fclose(fp);

return;
}


And how does this non-conforming, badly indented (learn to use Google
Broken Beta correctly or get a real newsreader!) code, with a
system-specific filename, help even the slightest bit with the OP's
problem, which is outputting the binary representation of an object?
Even if we assume a single interpretation of "binary representation"
(there are two reasonable ones), your code does not reliably output
either of those for all objects.

Richard
Nov 14 '05 #8
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
[...]
badly indented (learn to use Google Broken Beta correctly or get a
real newsreader!) code

[...]

Unfortunately, it's not possible to indent code correctly using Google
Broken Beta. You can work around it by prefixing each line with a '.'
character, or use groups.google.c a (which, last time I checked, still
uses the old interface), or, as you suggest, get a real newsreader.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
7551
by: Bill Loren | last post by:
Hello ppl, I'm having difficulties to accomplish some simple chores with binary data. I'm having a string (?) which I received via an HTTP transactions which is a binary file. Problem is the webserver I'm communicating with injected a \x0D before every \x0A, and I need to remove those 0x0D characters from my buffer before saving it to disk.
9
3198
by: Hans-Joachim Widmaier | last post by:
Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is indeed also true for our language of choice, Python. Its file type allows some extraordinary convenient access like: for line in open("blah"): handle_line(line)
7
3970
by: Matthias Czapla | last post by:
Hi! Whats the canonical way for handling raw data. I want to read a file without making any assumption about its structure and store portions of it in memory and compare ranges with constant byte sequences. _I_ would read it into arrays of unsigned char and use C's memcmp(), but as you see Im a novice C++ programmer and think that theres some better, typically used, way. Regards
0
2077
by: David List | last post by:
I am wondering what I miss to be able to handle binary data from the mysql client. I have ensured that the user has file_priv set to 'Y' and that max_allowed_packet is larger that the binary lumps handled. Here is my version: Ver 4.1.5-gamma-log for pc-linux on i686 (Source distribution) Right now I'm trying this to insert binary data: mysql> update table set col=load_file("/path/file") where id=1;
2
2520
by: Lisa Pearlson | last post by:
Hi, My php application (on Apache/Linux) needs to do the following: The PHP script receives a request from a client (binary), asking for certain records of data. My PHP script loops through all records and sends each of them ONE BY ONE. After each record that my server script sends, it waits for the client to confirm proper reception with an ACK (binary digit). When there are no more records, my server script sends the client a binary
4
1181
by: Shawn | last post by:
Hi All; i have created a class that handles file input and output. one of the methods loads data from a file then returns a hashtable filled with data class. it takes in the file name and the class of the data stored in the file. what i would like to know is: is there a way to make the function take a generic class without having to create a ton of overloaded versions of the method or using a switch statement and replicating the code?...
0
936
by: William Sullivan | last post by:
I'm doing ajax calls using a webpage that implements ICallbackEventHandler. I've set it up to run a javascript function client side when the process completes and when the process throws an exception. Within my server side client callback event handler, I do some data access and return a result. If the data access layer throws an exception (it may throw five different ones), I catch it, construct an appropriate message for the end user,...
2
2731
by: CharlesL | last post by:
I am trying to handle binary strings in php. I get a binary output initialization vector from mcrypt as such: from mcrypt: $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); This output may have padded nulls at the end which are significant. I would like to convert all characters including all padding nulls at end and convert it in a string to be saved into a database in such a way
9
3242
by: lokeshrajoria | last post by:
hello everybody, i need some help in binary file handling in perl. can anybody give me some information about binary file. actully i am reading data from some text file and extracting some usefull information from there and want store in my own binary file with .vbf extension ( not like .dat file.) i am putting code here for reading text file and extract some information from there but how can i store that information in my own binary file. ...
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8337
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8531
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8628
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7359
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2754
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.