Link to home
Start Free TrialLog in
Avatar of nofearse
nofearse

asked on

outputing to a binary file

I am trying to output a string to a binary file, but I have no idea how to do it at all
say if I have a string:
string A = "1010";
I want to output it as a byte to the binary file
and I need to format it as 00001010

I guess I need to extract it bit by bit from the string and somehow using bit operator to assign the bit to the byte, then output the byte to the binary file
But I can't find any reference on the web about that

Does anyone know how and give me an example of it?
Also, do I need to output it byte by byte to the binary file?

If I want to read a binary file and convert it back to a string or a character, how can I do it?
Avatar of jkr
jkr
Flag of Germany image

The easiest way would be to

#include <stdlib.h>
#include <string>
using namespace std;


//...


typedef unsigned char BYTE;

string A = "1010";
char* pcCnvEnd = NULL;

BYTE b = ( BYTE) strtol ( A.c_str (), &pcCnvEnd, 2);

if ( *pcCnvEnd) {

  // some error occured
}
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nofearse
nofearse

ASKER

where is the filestream?
how does bit operator <<  work?
confused :S
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Split: jkr {http:#9705654} & dude_1967 {http:#9714397}

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer