Member Avatar for elektro123

Hello!
I have small problem. I have char array which contains e.g. "10010010100010110" and I want to read/write it from/to file in binary mode. How can I convert my char array to a group of bits and how to write/read it to/from file?

I need something like this:
1. I have char array = "101010" => convert to bits - 101010 => write bits to file in binary mode
2. Read bits from file => convert to char array.

Thanks in advance!

you don't have to convert anything -- just write the array to a file as it is. BTY: you can not write bits to a file -- only bytes.

Member Avatar for elektro123

Like this?:

void save()
{
 char a[] ={"101001"};
     
     ofstream file("test.bin", ios::out | ios::binary);
     file.write(a,strlen(a));   
     file.close();
      
}

Because I don't think so... My file should contain "Ő" (or similar), but it cointais 1001010...

What am I doing wrong?

Looks like what you really want is to convert that string into an integer then write the binary value of the integer. See this link for more info about strtol()

char num[] = "01011";
char* ptr;
int x = strtol(num,&ptr,2);
out.write((char*)&x,sizeof(int));
Member Avatar for elektro123

Looks like what you really want is to convert that string into an integer then write the binary value of the integer. See this link for more info about strtol()

char num[] = "01011";
char* ptr;
int x = strtol(num,&ptr,2);
out.write((char*)&x,sizeof(int));

Thanks You very much! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.