473,765 Members | 2,005 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing Numbers to a Binary File

rob
hey every1,

I've got alot of data to write out to file and it's all just 1's and
0's.

It's all stored in 2 dimensional arrays of width 32 and varying
height.

At the moment it's all just integer arrays and the individual 1's and
0's are being written out as integers.

I was just wondering how i cud write them out as actual binary bits
and hence save on the eventual file size.

I've got something like this at the moment....

int main()
{
FILE* dude;

dude = fopen("Bin.dat" , "wb");

int swap_a[4][32];

for(int e = 0; e < 4; e++){
for(int d = 0; d < 32; d=d+2){
swap_a[e][d] = 0;
swap_a[e][d+1] = 1;
}
}

for(int j=0; j<4; j++){
for(int d=0; d<32; d++){
fprintf(dude, "%i", swap_a[j][d]);
printf("%i", swap_a[j][d]);
}
fprintf(dude, "\n");
printf("\n");
}

return 1;
}

but all that does is create a file like:

010101010101010 101010101010101 01
010101010101010 101010101010101 01
010101010101010 101010101010101 01
010101010101010 101010101010101 01
How do i write each 1 or 0 as an actual bit so that they don't take up
as much space in the files as an integer?

Any help wud be well appreciated (sorry for the FILE* usage, just
moved from C)

Thanx,

Rob.
Jul 22 '05 #1
5 5564
rob wrote:
hey every1,

I've got alot of data to write out to file and it's all just 1's and
0's.

It's all stored in 2 dimensional arrays of width 32 and varying
height.

At the moment it's all just integer arrays and the individual 1's and
0's are being written out as integers.

I was just wondering how i cud write them out as actual binary bits
and hence save on the eventual file size.

I've got something like this at the moment....

int main()
{
FILE* dude;

dude = fopen("Bin.dat" , "wb");

int swap_a[4][32];

for(int e = 0; e < 4; e++){
for(int d = 0; d < 32; d=d+2){
swap_a[e][d] = 0;
swap_a[e][d+1] = 1;
}
}

for(int j=0; j<4; j++){
for(int d=0; d<32; d++){
fprintf(dude, "%i", swap_a[j][d]);
printf("%i", swap_a[j][d]);
}
fprintf(dude, "\n");
printf("\n");
}

return 1;
}

but all that does is create a file like:

010101010101010 101010101010101 01
010101010101010 101010101010101 01
010101010101010 101010101010101 01
010101010101010 101010101010101 01
How do i write each 1 or 0 as an actual bit so that they don't take up
as much space in the files as an integer?

Any help wud be well appreciated (sorry for the FILE* usage, just
moved from C)

Thanx,

Rob.


You are using text mode for writing to the file. The
fprintf function converts from binary (native) format
to text format.

Use the fwrite function:
fwrite(swap_a, sizeof(swap_a), 1, dude);
Be sure to check the return value.

Also, when writing out as binary, don't append '\n'
to the output.

When opening a file in binary mode, you are just
telling the I/O system not to translate any characters.
Some platforms translate '\n' into '\r\n' and vice
versa.

Also, when you get a chance, look at the fstream
and iostream classes. They are the C++ streams.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 22 '05 #2
rob wrote:

hey every1,

I've got alot of data to write out to file and it's all just 1's and
0's.

It's all stored in 2 dimensional arrays of width 32 and varying
height.

At the moment it's all just integer arrays and the individual 1's and
0's are being written out as integers.

I was just wondering how i cud write them out as actual binary bits
and hence save on the eventual file size.


By eg. collecting 8 of them and forming an unsigned char of them

eg.

unsigned char Bits = Bit0 << 7 |
Bit1 << 6 |
Bit2 << 5 |
Bit3 << 4 |
Bit4 << 3 |
Bit5 << 2 |
Bit6 << 1 |
Bit7;

Also note, that you might want to use fwrite instead of fprintf to
write the bits.

fwrite( &Bits, 1, 1, dude ); // look Ma, 8 of my bits only account for
// 1 Byte on the file
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #3
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Rob,

Well, first, I'm going to use the C++ container called bitset provided
by Boost. Then, I'm going to use the iostreams library to write out the
data in binary format.

I chose the boost::dynamic_ bitset library because it has the option of
creating a runtime sized "container" of bits which can then be striped
from the "container" in block format, where the blocks are some integral
time like unsigned int. Finally, by using the iostream write function,
the data is sent to the output file in binary format.

rob wrote:
hey every1,

I've got alot of data to write out to file and it's all just 1's and
0's.

It's all stored in 2 dimensional arrays of width 32 and varying
height.

At the moment it's all just integer arrays and the individual 1's and
0's are being written out as integers.

I was just wondering how i cud write them out as actual binary bits
and hence save on the eventual file size.

I've got something like this at the moment....

int main()
{
FILE* dude;

dude = fopen("Bin.dat" , "wb");

int swap_a[4][32];

for(int e = 0; e < 4; e++){
for(int d = 0; d < 32; d=d+2){
swap_a[e][d] = 0;
swap_a[e][d+1] = 1;
}
}

[snip]


//C++ news group bitset operations

#include <fstream>
#include <boost/dynamic_bitset. hpp>

using namespace std;
using namespace boost;

int main(){
typedef unsigned int block;
typedef dynamic_bitset< block> bitset;
typedef block BlockItor;

int numblocks = 4;
bitset swap_a(numblock s); //make a bitset 4 ints long...All bits
default to 0
ofstream dude("Bin.dat") ;
BlockItor outitor;

//Now, set every other bit to 1 (actually, this doesn't work,
//but you get the idea.
for (int i = 0; i < (swap_a.num_blo cks() * sizeof(block)); i++)
swap_a[i].flip();

//Finally, grab the blocks off the set & write them out to the stream
to_block_range( swap_a, &outitor);
for(int i = 0; i < swap_a.num_bloc ks(); i++){
dude.write((con st void *)&outitor, sizeof(block));
outitor++;
}
dude.close();
return 0;
}
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFALO8joo/Prlj9GScRArcSAJ 0cq4gLHcKsptbV8 sGivxPryOyxaACe KqA6
qnUO7NxC9hKa/waeI0l2Gdw=
=m9j2
-----END PGP SIGNATURE-----
Jul 22 '05 #4
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Darn it! I flubbed a critical part of the output where the iterator is
advancing. Correction to previous code below.

Evan Carew wrote:

//Finally, grab the blocks off the set & write them out to the stream
to_block_range( swap_a, &outitor);
for(int i = 0; i < swap_a.num_bloc ks(); i++){
dude.write((con st void *)&outitor, sizeof(block));
outitor++;
}

Should read:

//Finally, grab the blocks off the set & write them out to the stream
to_block_range( swap_a, &outitor);
for(int i = 0; i < swap_a.num_bloc ks(); i++){
dude.write((con st void *)&outitor, sizeof(block));
to_block_range( swap_a, &outitor);
}
Sorry about that.

Evan Carew
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFALO/0oo/Prlj9GScRAg80AJ 9cPcAjsqN/2QPfbIZx4t92hCt PTQCeK2Yv
QOBcZ4zG/WDaqIUBSl7pdlo=
=mq/l
-----END PGP SIGNATURE-----
Jul 22 '05 #5
I had done something similar in the past. Here's a function I wrote:

/*************** *************** *************** *************
FUNCTION: packint
DESCRIPTION: Takes in an array of 32bit integers, and puts them into a
serialized binary string structure.
INPUT: char array pointer, int array pointer, int array size
OUTPUT: (modifies char array pointer)
SYNTAX:
packint( binary result string, array of int, # of array elements);
*************** *************** *************** ************/
void packint (u_char *buffer, const unsigned long int *intarray, const
unsigned long int size)
{
unsigned long int c, i;

c = 0;
for(i = 0 ; i < size; i++)
{
buffer[c]=(u_char)(intar ray[i] >> 24);
buffer[c+1]=(u_char)(intar ray[i] >> 16);
buffer[c+2]=(u_char)(intar ray[i] >> 8);
buffer[c+3]=(u_char)(intar ray[i]);
c=c+4;
}
}
All you have to do now is just write the result string to a BINARY file
or a database. You could even process the string thru a compression
function to save even more space.

Of course I was storing 32-bit wide numbers, but it could easily be
modified for any bit size (24, 16 or 8-bit) if you know your max ranges.

-John_JR



Thomas Matthews wrote:
rob wrote:
hey every1,

I've got alot of data to write out to file and it's all just 1's and
0's.

It's all stored in 2 dimensional arrays of width 32 and varying
height.

At the moment it's all just integer arrays and the individual 1's and
0's are being written out as integers.

I was just wondering how i cud write them out as actual binary bits
and hence save on the eventual file size.

I've got something like this at the moment....

int main()
{
FILE* dude;

dude = fopen("Bin.dat" , "wb");

int swap_a[4][32];

for(int e = 0; e < 4; e++){
for(int d = 0; d < 32; d=d+2){
swap_a[e][d] = 0;
swap_a[e][d+1] = 1;
}
}

for(int j=0; j<4; j++){
for(int d=0; d<32; d++){
fprintf(dude, "%i", swap_a[j][d]);
printf("%i", swap_a[j][d]);
}
fprintf(dude, "\n");
printf("\n");
}

return 1;
}

but all that does is create a file like:

010101010101010 101010101010101 01
010101010101010 101010101010101 01
010101010101010 101010101010101 01
010101010101010 101010101010101 01
How do i write each 1 or 0 as an actual bit so that they don't take up
as much space in the files as an integer?

Any help wud be well appreciated (sorry for the FILE* usage, just
moved from C)

Thanx,

Rob.

You are using text mode for writing to the file. The
fprintf function converts from binary (native) format
to text format.

Use the fwrite function:
fwrite(swap_a, sizeof(swap_a), 1, dude);
Be sure to check the return value.

Also, when writing out as binary, don't append '\n'
to the output.

When opening a file in binary mode, you are just
telling the I/O system not to translate any characters.
Some platforms translate '\n' into '\r\n' and vice
versa.

Also, when you get a chance, look at the fstream
and iostream classes. They are the C++ streams.


Jul 22 '05 #6

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

Similar topics

3
17622
by: Michael Weir | last post by:
I'm sure this is a very simple thing to do, once you know how to do it, but I am having no fun at all trying to write utf-8 strings to a unicode file. Does anyone have a couple of lines of code that - opens a file appropriately for output - writes to this file Thanks very much. Michael Weir
13
5806
by: E-Star | last post by:
I have a binary file that I want to read some numbers out of. However the numbers are 32bit floats. How can I get the numbers into a C program to use? I can do the calculations manually....but is there an easier way? Is there some handy functions which do this? example. File contains: 42 7C 00 00 I want to read it in and end up with my C variable equalling 63.
6
23603
by: Sebastian Kemi | last post by:
How should a write a class to a file? Would this example work: object *myobject = 0; tfile.write(reinterpret_cast<char *>(myobject), sizeof(*object)); / sebek
2
2198
by: Mitch | last post by:
Hi all, I hope this is the right place for this post, apologies if it is not. I am trying to write a program that creates an input file for a dispersion model. The model is expecting a Fortran "unformatted" binary file in big-endian. However, my program is written in dotnet and I'd like to avoid writing and then calling a Fortran program to do this one task. My question is:
3
5504
by: Romain | last post by:
Hello, I am writing out a binary file. I figured that the number "10" is automaticaly converted to "OD OA" instead of "OD". "OD" and "OA" are line feed and carriage return. I know it does that if the file is opened in something else than in binary mode. But in my example below, the file is really opened in binary.
29
3575
by: Glen | last post by:
Is it possible to write a structure to a file in c...as in c++...?? is it using fwrite?? thanx glen
1
5837
by: Steve Bostedor | last post by:
I'm trying to use the RegistryKey to write a hex number into the registry as a binary type. I know see that in DotNet, the RegistryKey tries to interprate what registry type to create depending on the type of structure the variable was dimmed as. I dimmed it as a character array, then dumped each value into that character array, then wrote it to the registry and sure enough, it created a binary entry of it .... but .... The problem...
3
18961
by: nicolasg | last post by:
Hi, I'm trying to open a file (any file) in binary mode and save it inside a new text file. After that I want to read the source from the text file and save it back to the disk with its original form. The problem is tha the binary source that I extract from the text file seems to be diferent from the source I saved. Here is my code: 1) handle=file('image.gif','rb')
6
5272
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
0
9404
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
10164
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...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9959
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
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5277
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...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3926
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
3
2806
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.