Can i write single BITs TO a binary FILE - It is urgent but i don't have so many points :(

Posted on 2003-03-19
Medium Priority
Last Modified: 2010-04-01

I have a string of bit values (like: 00010001). Now i would like to write them to a binary file. I have no idea how can i do this. Can i write to a file just bit values? If not how can i make a BYTE with the same value so i culd write it to the file.

Thanx a lot
Question by:Kockica
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Accepted Solution

DarthNemesis earned 225 total points
ID: 8170646
All files, even binary types, work by storing bytes, so using an entire byte to store one bit would be inefficient. However...

<plug>You could use my handy-dandy BASENUM class to convert the binary string to a decimal value!</plug>

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

class BASENUM {
        long value;
        BASENUM() : value(0) {}
        BASENUM(int v) : value(v) {}
        BASENUM(string s, int base) {
                this->setValue(s, base);
        BASENUM(const BASENUM &bn2) {
                this->value = bn2.value;
        void setValue(string s, int base) {
                value = 0;
                for (int i=s.length()-1; i>=0; i--) {
                        if (i==0 && s[0] == '-') value = 0 - value;
                        int digitval = digits.find(s[i]);
                        if (digitval == -1) continue;
                        value += digitval*pow(base,s.length()-1-i);
        int getValue() const {
                return value;
        string toBase(int base) {
                int tempvalue = value;
                string s = "";
                if (value < 0) tempvalue = 0 - tempvalue;
                while (tempvalue > 0) {
                        char newchar = digits[tempvalue%base];
                        s = newchar + s;
                        tempvalue /= base;
                if (value < 0) s = "-" + s;
                return s;
        const BASENUM & operator = (const BASENUM & bs2) {
                value = bs2.value;
                return *this;
BASENUM operator +(const BASENUM bs1, const BASENUM bs2)
    BASENUM bs3 = bs1.getValue() + bs2.getValue();
    return bs3;

void main() {
        string s = "00010001";
        BASENUM n(s,2); // string, base (in this case binary)
        ofstream outfile("filename.txt");
        outfile << n.toBase(10) << endl;

Expert Comment

ID: 8170668
Oh, if you want to store it as a single byte, change outfile << n.toBase(10) << endl; to outfile << byte(n.getValue()) << endl;

Expert Comment

ID: 8171019
This may give you some ideas.  It's not pretty, but it should be fast...:

#include <iostream.h>
#include <conio.h>

struct Bits {
  unsigned b0 : 1;
  unsigned b1 : 1;
  unsigned b2 : 1;
  unsigned b3 : 1;
  unsigned b4 : 1;
  unsigned b5 : 1;
  unsigned b6 : 1;
  unsigned b7 : 1;

union BitConversion {
  Bits b;
  unsigned char byte;

unsigned char toByte( char* buffer ) {
  BitConversion x;
  x.b.b0 = buffer[0]=='1';
  x.b.b1 = buffer[1]=='1';
  x.b.b2 = buffer[2]=='1';
  x.b.b3 = buffer[3]=='1';
  x.b.b4 = buffer[4]=='1';
  x.b.b5 = buffer[5]=='1';
  x.b.b6 = buffer[6]=='1';
  x.b.b7 = buffer[7]=='1';
  return x.byte;

int main()
  char *value = "00010001";
  unsigned char expectedByte = 0x11;

  unsigned char byte = toByte( value );


  return 0;
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Expert Comment

ID: 8171026
For some reason my compiler returned 0x88 instead of 0x11, perhaps the bits in the struct get saved in reverse order...

Expert Comment

ID: 8172025
arjkane, thank you for pointing out the endian-ness assumption already.  :)  Depending on the format of the input (are there always 8 numbers for each byte, is MSB on the left, etc?), and whether the output can depend on endian-ness, your approach will be different.  If you want to do what I think you want to do, you'd do this: (tongue-twister!)

int idxInputBuf, shiftCount;
unsigned char outVal;

for (idxInputBuf = 0; idxInputBuf < bufSize; idxInputBuf++)
  outVal = 0;
  for (shiftCount = 0; shiftCount < 8; shiftCount++)
    if (inputBuf[idxInputBuf] == '1')
      outVal += 1;
    outVal << 1;
  //use outVal here

Author Comment

ID: 8172767
A big thank to all

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question