By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,379 Members | 3,035 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,379 IT Pros & Developers. It's quick & easy.

how to store 1 bit at a time in a file C++

P: 11
hii
i am a student doing a project, part of which requires storing certain sequence of bits.. only 1s and 0s in a file ... how can i do it ( in C++) so that the memory needed for each 1 or 0 is only 1 bit ,, not bytes ..
I would be glad for any help.... I am fairly new to C++.
Jun 12 '07 #1
Share this Question
Share on Google+
8 Replies


P: 7
Take 8 bits at a time, convert it to value and then to char
Store that char in the file.
e.g.: 11001100 = 204(in decimal)
insert char(204) into the file.
If last fetched bits are less than 8, append 0's in front.

While reading the file, convert the char to binary, you will get all the bits

You can only write character into the file.
Jun 12 '07 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
Use the bitset template.

Expand|Select|Wrap|Line Numbers
  1. bitset<32> switches;
  2.  
The bitset object above has 32 bits.
Jun 12 '07 #3

P: 11
Use the bitset template.

Expand|Select|Wrap|Line Numbers
  1. bitset<32> switches;
  2.  
The bitset object above has 32 bits.
Can u plz expln a bit about the bitset template ..
Jun 13 '07 #4

P: 7
Use the bitset template.

Expand|Select|Wrap|Line Numbers
  1. bitset<32> switches;
  2.  
The bitset object above has 32 bits.

bitset<> can be used while reading from file but not while writing into the file in this case, since bitset will take unsigned long as an argument and convert it into bit format.
It can convert from unsigned long to bits but not from bits to char.
Jun 13 '07 #5

P: 7
You can use the algorithm used by JPEG if you want optimization.
That will be cool
Jun 14 '07 #6

P: 4
hai
i want to display binary equivalent number in c programming.
so please give me response as early as possible.
Jun 14 '07 #7

P: 4
hai
i want to display binary equivalent number in c programming.
so please give me response as early as possible.i laerning c now. so please give me response on bitwise means reversing, setting,clear the bits etc...,
Jun 14 '07 #8

weaknessforcats
Expert Mod 5K+
P: 9,197
bitset<> can be used while reading from file but not while writing into the file in this case, since bitset will take unsigned long as an argument and convert it into bit format.
It can convert from unsigned long to bits but not from bits to char.
It can convert bits to char but each bit is one char.

Expand|Select|Wrap|Line Numbers
  1. bitset<32> switches;
  2. string str;
  3. str =  switches.template to_string<char, 
  4.          char_traits<char>, allocator<char> >( );
  5.  
Jun 14 '07 #9

Post your reply

Sign in to post your reply or Sign up for a free account.