How to store a binary string in binary form in a file?

I have a problem storing a binary string. How to save binary string "100010101010000011100" in binary form in a file using C?

Besides one line, if I have two lines, how can I save these two lines together? Thank you for your help.

+3
source share
4 answers

You can write a bit 8to a variable unsigned charand write it to a 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++;
}
+2
source

Um, I'm not sure if I understand your question. You ask HOW to store a string in a file using C, or you ask the best way to encode binary data to store files?

If the first one, I suggest the following resources:

, , , , , .

EDIT: , .

0

Open the file for writing in binary mode.

Convert the binary string to an integer and write it to a file

0
source

This one supports binary strings of arbitrary length, but of course has many drawbacks, especially. when considering reading from a file. :) It should be good enough for a starter.

#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);
};
0
source

Source: https://habr.com/ru/post/1741752/


All Articles