tags:

views:

196

answers:

5

Hello all, i have a problem on storing binary string. How can i store binary string "100010101010000011100", in the binary form, in a file using C ?

Apart from just one string, if i have two strings, how can i store these two strings together? Thanks for your help.

A: 

char *p;

p="100010101010000011100"

orr

char A[]="100010101010000011100"

or

if alot of binary input

define max1 100

define max2 100

{ char *p; char A[max1][max2];

for(;*p!='\0';++p)

gets(p); A[i]=p;

gcc
Use the code tag.
Andrei Ciobanu
So you're using `gets` (which you should *never* use), and moreover, you're having it write to an uninitialized pointer. Great.
jamesdlin
A: 

Erm, I am not sure if I understand your question. Are you asking HOW to store a string in a file using C or are you asking the best way to encode binary data for file storage?

If the former, I suggest the following resources:

If the latter, then there are numerous encoding methods and standards, but frankly I don't see why you don't just store your binary string as-is.

EDIT: Think about it again, the obvious solution would be to convert your binary number into an integer or hex and store that.

Konrad
A: 

Open the file for writing in binary mode.

Convert your binary string into integer and write that to the file

Jasmeet
On Linux there's no need for opening the file for writing in binary mode, as "b" is ignored by default.
Andrei Ciobanu
+2  A: 

You can stuff 8 bits into an unsigned char variable and write that to the file.

unsigned char ch=0;
char bin[] = "100010101010000011100";
int i=0;

while(bin[i]) {
  if(i%8 == 0) {
    // write ch to file.
    ch = 0;
  }else {
   ch = ch | (bin[i] - '0');
   ch = ch << 1;
  }
  i++;
}
codaddict
A: 

This one supports binary strings of arbitrary lengths, but of course has many deficiencies, esp. when considering reading back from file. :) Should be good enough for a starter, though.

#include <string.h>
#include <fcntl.h>
#include <stdlib.h>

char A[]="111100000000111111";

int main() {
    unsigned int slen = strlen(A);
    unsigned int len = slen/8 + !!(slen%8);
    unsigned char * str = malloc(len);

    unsigned int i;
    for (i = 0; i < slen; i++) {
        if (!(i%8))
            str[i/8] = 0;
        str[i/8] = (str[i/8]<<1) | (A[i] == '1' ? 1 : 0);
    }
    if (slen%8)
        str[len-1] <<= (8-slen%8);

    int f = open("test.bin", O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU);
    write(f, str, len);
    close(f);
};
Mart Oruaas