473,657 Members | 2,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to save int in a more compact way

A int in memory takes 32bits (4 bytes).

But if I use ofstream to save a int like this:

int i=1234567890;
ofstream ofs("c:\\intdat a.bin", ios::binary);
ofs<<i;

It becomes 10 bytes in a file.

Is there any way to save a int or double in a more compact way? Thanks.

Nov 22 '06 #1
9 2302
* li********@gmai l.com:
A int in memory takes 32bits (4 bytes).
With your compiler.

But if I use ofstream to save a int like this:

int i=1234567890;
ofstream ofs("c:\\intdat a.bin", ios::binary);
ofs<<i;

It becomes 10 bytes in a file.
Binary mode doesn't affect the conversion to/from text. It affects the
translation of e.g. end-line markers that's done at a lower level.
You're employing operator<<, and that converts the value to text.

Is there any way to save a int or double in a more compact way?
Yes, but using a textual format is more portable and more accessible to
other tools (not the least text editors), and storage is cheap. It
could matter though for transmission over a network. But even there,
the trend is from binary to textual representations such as XML/SOAP.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 22 '06 #2
linyanhung wrote:
>A int in memory takes 32bits (4 bytes).
On many platforms, yes. On some platforms it's a different bit count.
But if I use ofstream to save a int like this:

int i=1234567890;
ofstream ofs("c:\\intdat a.bin", ios::binary);
ofs<<i;

It becomes 10 bytes in a file.
Right. The 'ios::binary' doesn't mean it will be a binary file. It just
means that <<"\n" will not (on some platforms) inexplicably write "\r\n".

So << i just formats the integer as a string.
Is there any way to save a int or double in a more compact way?
Yes, but I won't tell you what it is. Write and read integers as delimited
text, as often as you can, for as many programs as you can before learning
to write binary files.

There is no reason, while you are learning C++, or writing your first
programs, to worry about the size or speed of programs. Google for the term
"premature optimization is the root of all evil", to learn why. Then write
large files that are easy to program.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Nov 22 '06 #3
If you insist in encoding the integer in text like convert 1234 to
"1234" by itoa, maybe you can try BCD to encode the string into the
more concise format.
eg: in BCD, "1234" can be encoded into an array {0x43, 0x21} with two
bytes. Actually, BCD can help you save the half of space.

On 11ÔÂ22ÈÕ, ÏÂÎç1ʱ06·Ö, linyanh...@gmai l.com wrote:
A int in memory takes 32bits (4 bytes).

But if I use ofstream to save a int like this:

int i=1234567890;
ofstream ofs("c:\\intdat a.bin", ios::binary);
ofs<<i;

It becomes 10 bytes in a file.

Is there any way to save a int or double in a more compact way? Thanks.
Nov 22 '06 #4
HaHaHa Thanks you very much!

So still no one tell me how to do it.

In fact, I need to save more than 250000000 ints in my file. The file
will become too big to handle.

So, is there any one can tell me how to do it? :)

Phlip ¼g¹D¡G
linyanhung wrote:
A int in memory takes 32bits (4 bytes).

On many platforms, yes. On some platforms it's a different bit count.
But if I use ofstream to save a int like this:

int i=1234567890;
ofstream ofs("c:\\intdat a.bin", ios::binary);
ofs<<i;

It becomes 10 bytes in a file.

Right. The 'ios::binary' doesn't mean it will be a binary file. It just
means that <<"\n" will not (on some platforms) inexplicably write "\r\n".

So << i just formats the integer as a string.
Is there any way to save a int or double in a more compact way?

Yes, but I won't tell you what it is. Write and read integers as delimited
text, as often as you can, for as many programs as you can before learning
to write binary files.

There is no reason, while you are learning C++, or writing your first
programs, to worry about the size or speed of programs. Google for the term
"premature optimization is the root of all evil", to learn why. Then write
large files that are easy to program.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Nov 22 '06 #5
* li********@gmai l.com:
[top-posting]
See FAQ item 5.4.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 22 '06 #6
linyanhung wrote:
HaHaHa Thanks you very much!
Welcome to USENET. ;-)
So still no one tell me how to do it.
In fact, I need to save more than 250000000 ints in my file. The file
will become too big to handle.

Why so many ints? I have been programming for almost 20 years and I never
saved so many.

Oh, yeah, I did for JGA. I invented a file format that stored the difference
between each successive int as a character delta. The ints were expected to
mostly have similar values, and only occassionally differ, so I stored a
stream of deltas, and if any delta were 0xff, the next four bytes were the
entire int.

To stop formatting your ints as strings, start with ofs.write( something &i,
sizeof i);

I forget what something is. It might be a typecast to char *.

When I Google for [ofstream write binary], the very first page is this:

http://www.angelfire.com/country/ald...aryFileIO.html

Its title: C++ Binary File I/O

Dig in!

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Nov 22 '06 #7
Thanks for your answer.

I am now making a model about rice production. I need to calculate and
output data of more than twenty years in 500*500 grids (Something like
GIS). That's why I have so many ints.

Nov 22 '06 #8
linyanhung wrote:
Thanks for your answer.

I am now making a model about rice production. I need to calculate and
output data of more than twenty years in 500*500 grids (Something like
GIS). That's why I have so many ints.
A finite element simulation? I thought you should use a "sparse array" for
that, because the rice ain't everywhere.

But if stomping in a 500^2 grid works, do it!

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Nov 22 '06 #9
li********@gmai l.com wrote:
A int in memory takes 32bits (4 bytes).

But if I use ofstream to save a int like this:

int i=1234567890;
ofstream ofs("c:\\intdat a.bin", ios::binary);
ofs<<i;

It becomes 10 bytes in a file.

Is there any way to save a int or double in a more compact way?
Yes. You may start by pondering on the following proof of concept. Error
handling is not done. Untested code -- use at your own risk.
#include <cstring>
#include <iostream>
#include <cstddef>

template < typename POD >
class io_converter {

char the_data [ sizeof(POD) ];

friend
std::ostream & operator<< ( std::ostream & o_str,
io_converter const & ic ) {
o_str.write( ic.the_data, sizeof(POD) );
return ( o_str );
}

friend
std::istream & operator>( std::istream & i_str,
io_converter & ic ) {
i_str.read( ic.the_data, sizeof(POD) );
return ( i_str );
}
public:

io_converter ( void )
{
std::memset( &the_data, 0, sizeof(POD) );
}

io_converter ( POD const & data )
{
get( data );
}

void get ( POD const & data ) {
std::memcpy( &the_data, &data, sizeof(POD) );
}

void put ( POD & data ) const {
std::memcpy( &data, &the_data, sizeof(POD) );
}

POD value ( void ) const {
POD result;
put( result );
return ( result );
}

};

#include <fstream>

int main ( void ) {
io_converter<in tic;
{
std::ofstream file ( "test.bin", std::ios::binar y );
for ( int i = 0; i < 1000; ++i ) {
ic.get( i );
file << ic;
}
}
{
std::ifstream file ( "test.bin", std::ios::binar y );
while ( file >ic ) {
std::cout << ic.value() << '\n';
}
}
}

Of course, this is inefficient in that it copies the data in memory around
without a purpose. So alternatively, you may also want to ponder about
this:

#include <cstring>
#include <iostream>
#include <cstddef>

template < typename POD >
class binary_wrapper {

POD & the_data;

friend
std::ostream & operator<< ( std::ostream & o_str,
binary_wrapper const & ic ) {
o_str.write( static_cast<cha r*>( static_cast<voi d*>( &ic.the_data ) ),
sizeof(POD) );
return ( o_str );
}

friend
std::istream & operator>( std::istream & i_str,
binary_wrapper & ic ) {
i_str.read( static_cast<cha r*>( static_cast<voi d*>( &ic.the_data ) ),
sizeof(POD) );
return ( i_str );
}
public:

binary_wrapper ( POD & data )
: the_data ( data )
{}

POD & value ( void ) {
return ( the_data );
}

POD const & value ( void ) const {
return ( the_data );
}

};

#include <fstream>

int main ( void ) {
{
std::ofstream file ( "test.bin", std::ios::binar y );
int i = 0;
binary_wrapper< intbw ( i );
for ( ; i < 1000; ++i ) {
file << bw;
}
}
{
int i;
binary_wrapper< intbw ( i );
std::ifstream file ( "test.bin", std::ios::binar y );
while ( file >bw ) {
std::cout << i << '\n';
}
}
}
BTW: you really shouldn't be doing this.
Best

Kai-Uwe Bux
Nov 22 '06 #10

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

Similar topics

13
5069
by: James Franklin | last post by:
Hi, I have a number of databases in A2K, written on different machines with different installations of Office. I have found that compacting a database while it is open regularly fails, seemingly at random. This is especially annoying as I usually set the Compact on Close setting in Tools/Options to true. Has anyone else experienced this and is there a fix? Thanks for any help,
3
2371
by: Trevor Hughes | last post by:
Hello All I have a database (Access 2000, running on Win 2000), which suffers from bloat over a period of time. In order to solve the problem I set the option to compact on exit. This however has caused a problem. The permissions of the mdb file which are set to Everyone-Full control, are reset when the database is compacted. The end result is the the users get a message saying Access cannot locate the database. I can run it with...
2
2457
by: Greg Strong | last post by:
Hello All, I've written code in a test database with test data. Everything seems to be working except compact database in VB code per http://www.mvps.org/access/general/gen0041.htm. The reason I say this is the auto number fields are NOT being reset to zero. I delete the data from tables with action delete queries, then call the compact DB code which is followed by importing data to tables and subsequent append queries to other tables....
1
4818
by: robert demo via AccessMonster.com | last post by:
In my startup routine, I have the following code: s = CLng(FileLen(filespec) / 1000000) If s > 5 Then 'FIRST, BACKUP THE FRONT END If BackupFrontEnd = False Then Exit Function End If
6
2274
by: MLH | last post by:
I just used Tools / Database Utilities / Compact Database in Access 97 for the first time. Unlike Access 2.0, it does not ask me to furnish a filename for it to compact into. It just launched headlong into a process that, after the fact, had the result of overwriting the 44-meg previous size file into an 8-meg file of the same name. Has anyone ever experienced a data-loss during such a compact operation under A97? Surely, the access...
4
1639
by: Al | last post by:
Hi I need to save lots of images on potentially very large database. Therefore the storage space is very crucial. I need what is most compact way to save an image. Currently I am using something like thi Thanks in advanc A dim IoImageValue() As Byt ….get the bytes from InkPictureBox control myDataRow("Graph") = IoImageValu
5
3334
by: bob | last post by:
Hi Using 2003 - targeting the compact framework (c#), but would like to do most development using the full.net (manually leaving out stuff not in the compact framework). Q. Trying to find a way of converting a project to have builds for both compact and full. Project properties doesn't seem to help Thanks
6
4137
by: Josetta | last post by:
Access 2003 I've been experiencing some problems with my "monster" database the last couple of days. I imported all objects into a new database yesterday, which pretty much stopped the crashing problems, but here's something weird: Whenever I copy an object (reports so far), I am able to open it and make changes, but when I try to save it (without closing), it appears to save (message box goes off), but it doesn't. Then, if I try to...
2
2308
by: Karl | last post by:
Using A2000 When I click the save icon in form design, Access closes immediately. No warning messges, nothing. This happens on only one form. I deleted the form and recreated it. I could save the new form as Form1 but when I renamed it to the origianl forms name and click the save icon, Access closed. The form is based on a table that has several combo boxes. FWIW the table is
0
8403
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
8316
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,...
1
8509
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
8610
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
7345
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...
1
6174
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4168
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
4327
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2735
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

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.