3

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.

1
  • 1
    Convert to integer, store the integer. Commented Apr 19, 2010 at 10:05

4 Answers 4

2

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

Open the file for writing in binary mode.

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

1 Comment

On Linux there's no need for opening the file for writing in binary mode, as "b" is ignored by default.
0

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);
};

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.