1

I am trying to write a function that reads specified number of bytes from a binary file and converts them into a string of 1's and 0's. What is the easiest way to do that. File is in BigEndian.

string ReadBytesFromFile(int size)
{
    string result;
    ifstream file ("example.bin", ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {           
        memblock = new char [size];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();

        //need to convert memblock to binary string
        result = GetBinaryString(memblock);

        delete[] memblock;

    }
    return result;
}
2
  • Easiest way is probably using a bitset or itoa. Commented Sep 11, 2011 at 21:58
  • Remember to unset the skipws flag. Commented Sep 11, 2011 at 21:59

2 Answers 2

2

Call itoa() passing 2 as the radix. Make sure you don't overrun your buffer!

Note: This isn't part of any C or C++ standard so be warned it is not portable. But you asked for ease rather than portability!

Sign up to request clarification or add additional context in comments.

1 Comment

Not part of the standard library, but I am sure there are open-source implementations of it which you can use if you want it to be portable.
2

Take a byte at a time, and shift the bits off one by one.

Something like:

std::ostringstream ss;
for (int i=0; i<size; ++i) {
  char byte = memblock[i];
  for (int j=0; j<8; ++j) {
    ss << byte & 1;
    byte = byte << 1;    
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.