How to navigate through a binary file? - c

I have a text file written 10some information#11some more information#12and some more information#
10,11,12 are sentence id and should always be 2 bytes
I need to build a binary file from this text file, with the help of which I will then need to read sentences by id from a text file
In a binary file, each line should contain the following: sentence id, position of the beginning of the sentence, length of the string (sentence)
I managed to build a binary file, but I didn’t manage to read the information using it, the program shows that there are no such id, but I don’t understand why
#include <iostream>
#include <locale>
#include <string.h>
using namespace std;
int main()
{
FILE *poem, *index;
int N = 4096, len;
char *str= new char[N];
if (!(poem = fopen("poem.txt", "r")))
{
cout << "File not found";
return 0;
}
fgets(str, N, poem);
index = fopen("index.txt", "w+b");
int pos1 = 2, pos_b;
char* pos = str+pos1, *pstr=str;
fwrite(pstr, sizeof(char), 2, index);
fwrite(&pos1, sizeof(int), 1, index);
for (int i = 2; *pstr != '\0'; ++i, pstr++) {
if (*pstr == '#') {
len = pstr - pos;
fwrite(&len, sizeof(int), 1, index);
pos = pstr + pos1;
if (*(pstr+1)!='\0') {
fputs("\n", index);
fwrite(pstr+1, sizeof(char), 2, index);
pos_b = i + 3;
fwrite(&pos_b, sizeof(int), 1, index);
}
}
}
pos_b = 0;
len = 0;
fseek(index, 0, SEEK_SET);
fseek(poem, 0, SEEK_SET);
char* id = new char[3], * id_f = new char[3], * sent = new char[N];
int have_id = 0;
cout << "Enter the id of the offer you want to read" << endl;
cin >> id;
while (!feof(index)) {
fread(id_f, sizeof(char), 2, index);
if (strcmp(id_f,id)==0) {
fread(&pos_b, sizeof(int), 1, index);
fread(&len, sizeof(int), 1, index);
fseek(poem, pos_b, SEEK_SET);
fgets(sent, len + 1, poem);
cout << sent << endl;
have_id = 1;
}
else {
fread(id_f, sizeof(char), 3, index);
}
// fseek(index, 5, SEEK_CUR);
}
if (have_id == 0) {
cout << "There is no such id" << endl;
}
fclose(index);
fclose(poem);
delete[] str;
return 0;
}

Related

searching if arr is in a binary file c

I have a project; a kind of a anti-virus, to search whether a virus is in a file. My idea was to get a length of the virus and jump by one every time I reach the the length but I don't know how to do it exactly.
int virusChaek(FILE* file, char virus[],char filesNames[], int len)
{
char* pch;
int sizeOfFile = 0;
int i = 0;
int arr[100] = {0};
int* myArr;
int isVirus = 0;
file = fopen(filesNames, "rb");
if (file == NULL)
{
printf("file does not exist.");
return 1;
}
fseek(file, 0, SEEK_END);
sizeOfFile = ftell(file);
fseek(file, 0, SEEK_SET);
myArr = (int*)malloc(sizeof(int) * strlen(virus));
while (0 < (sizeOfFile))
{
fread(arr, 1, 1, file);
printf("arr[0] = %d\n", arr[0]);
myArr[i] = arr[0];
printf("myArr = %d\n", myArr[i]);
sizeOfFile--;
i++;
}
free(myArr);
fclose(file);
return 0;
}

Element disapears while calling a function - LZW Compression

I made some research but nothing was really concerning my problem...
I'm actually trying to code LZW compression for school, and I need a function to check if an element is in my dictionnary.
However, when I'm calling this function, it tries to access to the 64th element in my dictionnary, but it has desapeared !! I checked it before the function calling, it was here !! And the worse is that I can call this element in the previous callings of the function.
Could you help me please ?
The function :
int is_in_dictionnary(dico * p_pRoot, char * p_string){
int i = 0, j = 0;
char a[1024] = { 0 }, b[1024] = { 0 };
//strcpy(b, p_pRoot->m_dico[64].m_info);
for (i = 0; i < p_pRoot->m_index; i++){
printf("dico %s\n", p_pRoot->m_dico[i].m_info);
strcpy(a, p_string);
strcpy(b, p_pRoot->m_dico[i].m_info);
j = strcmp(a, b);
if (j == 0)
return i;
}
return -1;
}
The console, we are herer abble to see that the function previously called the 64th element "#", whithout any problem
The error on visual studio
Some people Asked me to add the code part where it's not functionning :
void lzw_compress(dico *p_pRoot, char * path)
{
FILE *pFile = NULL, *pCompFile = NULL;
int len_c = 0, size_tamp = 0, i = 0, masked_tamp = 0, tamp_to_write = 0, index_tamp = 0, a;
unsigned char char_tamp = 0, cAndTamp[1024] = { 0 }, tampon[1024] = { 0 }, c = '\0', temp[2] = { 0 };
char test[128] = { 0 };
pFile = fopen(path, "r+");
if (!pFile)
{
printf("problem while opening file to compress");
return;
}
size_t len = strlen(path); //creation of the output file name : paht+ ".lzw"
unsigned char *compress_name = malloc(len + 4 + 1);
strcpy(compress_name, path);
compress_name[len] = '.';
compress_name[len + 1] = 'l';
compress_name[len + 2] = 'z';
compress_name[len + 3] = 'h';
compress_name[len + 4] = '\0';
pCompFile = fopen(compress_name, "w"); //creation of the output file
free(compress_name);
while (1)
{
if (feof(pFile))
break;
c = freadByte(pFile);
for (i = 0; i < 1024; i++)
cAndTamp[i] = 0;
temp[0] = c;
strcat(cAndTamp, tampon);
strcat(cAndTamp, temp);
strcpy(test, p_pRoot->m_dico[64].m_info);
a = 0;
if (is_in_dictionnary(p_pRoot, cAndTamp) > -1)
{
strcpy(tampon, cAndTamp);
a = 0;
}
else
{
if (is_in_dictionnary(p_pRoot, tampon) < 256) //write the character in the file
{
char_tamp = tampon[0];
fwrite(&char_tamp, sizeof(char), 1, pCompFile);
a = 0;
}
else
{
a = 0;
index_tamp = is_in_dictionnary(p_pRoot, tampon);
a = 0;
for (i = 0; i < p_pRoot->m_size; i++)
{
mask = 1 << i;
masked_tamp = index_tamp & mask;
tamp_to_write = masked_tamp >> i;
fwriteBit(tamp_to_write, pCompFile);
flush(pCompFile);
}
}
strcpy(test, p_pRoot->m_dico[64].m_info); //HERE IT'S OK
add_dictionnary(p_pRoot, cAndTamp, size_tamp + 1); //add the string tamp + read byte in the dictionnay
strcpy(test, p_pRoot->m_dico[64].m_info); //HERE IT IS NOT OK
strcpy(tampon, temp);
}
strcpy(test, p_pRoot->m_dico[64].m_info);
size_tamp = is_in_dictionnary(p_pRoot, tampon);
}
if (tampon < 256) //write the character in the file
{
char_tamp = (char)tampon;
fwrite(&char_tamp, sizeof(char), 1, pCompFile);
}
else
{
index_tamp = is_in_dictionnary(p_pRoot, tampon);
for (i = 0; i < p_pRoot->m_size; i++)
{
mask = 1 << i;
masked_tamp = index_tamp & mask;
tamp_to_write = masked_tamp >> i;
fwriteBit(tamp_to_write, pCompFile);
flush(pCompFile);
}
}
fclose(pFile);
fclose(pCompFile);
}
The fucnction that where I think there is a problem
void add_dictionnary(dico * p_pRoot, char * p_string, int p_stringSize)
{
p_pRoot->m_index++;
if (p_pRoot->m_index == pow(2, p_pRoot->m_size))
realloc_dictionnary(p_pRoot);
p_pRoot->m_dico[p_pRoot->m_index].m_info = (char*)calloc(p_stringSize, sizeof(char));
strcpy(p_pRoot->m_dico[p_pRoot->m_index].m_info, p_string);
}
Another thank you guys !
I showed again the program to my teacher and he found the problem !
The problem is that i never use malloc and rarely use realloc so here was the problem :
void realloc_dictionnary(dico * p_pRoot)
{
int real = p_pRoot->m_size + 1;
int size = pow(2, real);
printf("index %d, previous pow %d, new power %d, size %d\n", p_pRoot->m_index, p_pRoot->m_size, real, size);
p_pRoot->m_dico = (code*) realloc(p_pRoot->m_dico, size);
p_pRoot->m_size = real;
}
size in a number of bits, ...
So the correction is : size * sizeof(code)!
void realloc_dictionnary(dico * p_pRoot)
{
int real = p_pRoot->m_size + 1;
int size = pow(2, real);
printf("index %d, previous pow %d, new power %d, size %d\n", p_pRoot->m_index, p_pRoot->m_size, real, size);
p_pRoot->m_dico = (code*) realloc(p_pRoot->m_dico, size * sizeof(code));
p_pRoot->m_size = real;
}
I would like to first of all say sorry because of this so little errror and also a big thanks for your great patience !

reverse content of file block by block

So here is the program to reverse content of a file block by block.
#include <stdio.h>
#include <stdlib.h>
#define BS 12
void reverse(char * buffer, int size)
{
char tmp;
int i;
for(i = 0; i < size / 2; i++)
{
tmp = (char)buffer[i];
buffer[i] = buffer[size - i - 1];
buffer[size - i - 1] = tmp;
}
}
int main (const int argc, const char** argv)
{
if(argc != 3)
exit(-1);
char * buffer = malloc(BS);
FILE * f1, * f2;
f1 = fopen(argv[1], "r");
f2 = fopen(argv[2], "w");
fseek(f1, 0, SEEK_END);
long i = ftell(f1);
// long f1_len = ftell(f1);
// unsigned char tmp;
int if_end = 1;
int need = 0;
int count;
do
{
i = i - BS;
if(i < 0)
{
need = BS - abs(i);
i = 0;
}
else
need = BS;
fseek(f1, i, SEEK_SET);
if(if_end) // strip EOF
{
count = fread(buffer, need - 1, 1, f1);
if_end = 0;
}
else
count = fread(buffer, need, 1, f1);
reverse(buffer, count);
fwrite(buffer, count, 1, f2);
if(i == 0)
break;
}while(i > 0);
fclose(f1);
fclose(f2);
free(buffer);
return 0;
}
testfile:
$ xxd testfile
0000000: 6162 6364 6566 670a abcdefg.
$ gcc test.c -o test
$ ./test testfile testfile2
$ xxd testfile2
0000000: 61 a
Any idea where is wrong? I have been debugging this for long time.
Your problem is that fwrite returns the number of successful blocks, not the number of bytes.
So reverse(buffer, count); needs to be reverse(buffer,count * need)
Similairly the write to the output needs to be fwrite(buffer, count * need, 1, f2);

Read and write 32bit wav file in C

I'm making a small program to read & write 32 bit wav file in C language.
But, I got a problem.
After compilation, Sometimes the program works well, yet sometimes, it doesn't work...like:
output wav file is empty
output wav file(1 sec) is too big, larger than 5GB...
I really stack here...
Anyone knows a solution??
Below is my program
↓ wave32.h ↓
typedef struct
{
int fs;
int bits;
int length;
double *s;
} MONO_PCM;
void wave_read_32bit_mono(MONO_PCM *pcm, char *file_name)
{
FILE *fp;
char riff_chunk_ID[4];
long riff_chunk_size;
char file_format_type[4];
char fmt_chunk_ID[4];
long fmt_chunk_size;
short wave_format_type;
short channel;
long samples_per_sec;
long bytes_per_sec;
short block_size;
short bits_per_sample;
char data_chunk_ID[4];
long data_chunk_size;
int data;
int n;
fp = fopen(file_name, "rb");
fread(riff_chunk_ID, 1, 4, fp);
fread(&riff_chunk_size, 4, 1, fp);
fread(file_format_type, 1, 4, fp);
fread(fmt_chunk_ID, 1, 4, fp);
fread(&fmt_chunk_size, 4, 1, fp);
fread(&wave_format_type, 2, 1, fp);
fread(&channel, 2, 1, fp);
fread(&samples_per_sec, 4, 1, fp);
fread(&bytes_per_sec, 4, 1, fp);
fread(&block_size, 2, 1, fp);
fread(&bits_per_sample, 2, 1, fp);
fread(data_chunk_ID, 1, 4, fp);
fread(&data_chunk_size, 4, 1, fp);
pcm->fs = samples_per_sec;
pcm->bits = bits_per_sample;
pcm->length = data_chunk_size / 4;
pcm->s = calloc(pcm->length, sizeof(double));
for (n = 0; n < pcm->length; n++)
{
fread(&data, 4, 1, fp);
pcm->s[n] = ( (double)data / 2147483648.0 ) ;
}
fclose(fp);
}
void wave_write_32bit_mono(MONO_PCM *pcm, char *file_name)
{
FILE *fp;
char riff_chunk_ID[4];
long riff_chunk_size;
char file_format_type[4];
char fmt_chunk_ID[4];
long fmt_chunk_size;
short wave_format_type;
short channel;
long samples_per_sec;
long bytes_per_sec;
short block_size;
short bits_per_sample;
char data_chunk_ID[4];
long data_chunk_size;
double s;
int data;
int n;
riff_chunk_ID[0] = 'R';
riff_chunk_ID[1] = 'I';
riff_chunk_ID[2] = 'F';
riff_chunk_ID[3] = 'F';
riff_chunk_size = 36 + pcm->length * 2;
file_format_type[0] = 'W';
file_format_type[1] = 'A';
file_format_type[2] = 'V';
file_format_type[3] = 'E';
fmt_chunk_ID[0] = 'f';
fmt_chunk_ID[1] = 'm';
fmt_chunk_ID[2] = 't';
fmt_chunk_ID[3] = ' ';
fmt_chunk_size = 16;
wave_format_type = 1;
channel = 1;
samples_per_sec = pcm->fs;
bytes_per_sec = pcm->fs * pcm->bits / 8;
block_size = pcm->bits / 8;
bits_per_sample = pcm->bits;
data_chunk_ID[0] = 'd';
data_chunk_ID[1] = 'a';
data_chunk_ID[2] = 't';
data_chunk_ID[3] = 'a';
data_chunk_size = pcm->length * 4;
fp = fopen(file_name, "wb");
fwrite(riff_chunk_ID, 1, 4, fp);
fwrite(&riff_chunk_size, 4, 1, fp);
fwrite(file_format_type, 1, 4, fp);
fwrite(fmt_chunk_ID, 1, 4, fp);
fwrite(&fmt_chunk_size, 4, 1, fp);
fwrite(&wave_format_type, 2, 1, fp);
fwrite(&channel, 2, 1, fp);
fwrite(&samples_per_sec, 4, 1, fp);
fwrite(&bytes_per_sec, 4, 1, fp);
fwrite(&block_size, 2, 1, fp);
fwrite(&bits_per_sample, 2, 1, fp);
fwrite(data_chunk_ID, 1, 4, fp);
fwrite(&data_chunk_size, 4, 1, fp);
for (n = 0; n < pcm->length; n++)
{
s = (pcm->s[n]) * 2147483648.0;
if (s > 2147483647.0)
{
s = 2147483647.0;
}
else if (s < -2147483647.0)
{
s = -2147483647.0;
}
data = (int)(s + 0.5);
fwrite(&data, 4, 1, fp);
}
fclose(fp);
}
↓ wave32.c ↓
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include "wave32.h"
int main(void)
{
MONO_PCM pcm0, pcm1;
int n;
wave_read_32bit_mono(&pcm0, "sine32.wav"); // 1 sec sine wave
pcm1.fs = pcm0.fs;
pcm1.bits = pcm0.bits;
pcm1.length = pcm0.length;
pcm1.s = calloc(pcm1.length, sizeof(double));
for (n = 0; n < pcm1.length; n++)
{
pcm1.s[n] = pcm0.s[n];
}
wave_write_32bit_mono(&pcm1, "b.wav");
free(pcm0.s);
free(pcm1.s);
return 0;
}
I guess your platform has long with size 8 bytes.
You can simply check it with:
printf("Long= %zu bytes - int= %zu bytes\n", sizeof(long), sizeof(int));
Then when you use, e.g
fread(&riff_chunk_size, 4, 1, fp);
You are wrongly reading the value, due to the endianness.
Switch all long types to int or better add
#include <stdint.h>
and change your variable types to:
long -> int32_t
int -> int32_t
short -> int16_t

How to convert LSB extracted data to text or binary to text

UPDATE***********************
For reference I included the program I made for opening a PPM image - embedding a message into the image and then saving out a new image with the embedded text. With the function below I'm hoping to extra that message, (hidden in the LSB) and then converting it to text to display it. Thanks for the replies so far - I'm going to start testing them out and see if anything works.
I'm trying to write a function that extracts the LSB of an unsigned char value - puts them bits together to form an extracted message. I have the length of how many LSBs I need to extract from the file, but I'm having trouble with how to convert this into a message.
At first I extracted the first 8 bits into an int array - giving me something such as 00110000. Now I have an INT array with that value, and I need to convert it to a single char for the letter representation. However, I think I should be taking in all of the LSBs into an array that is messageLength * 7 and somehow converting that int array into the text. It would be giving me the binary represenation of the text before converting. Maybe theirs a way to convert a long string of 1's and 0's to text?
unsigned char * extBits(PPMImage *img, int messageLen, unsigned char * decMsg)
{
//int count = 2;
int embCount = 0;
int deM = messageLen * 7;
int count = 0;
unsigned char byte;
// int mask;
// unsigned char update;
// unsigned char flipOne = 0x01; //0x01
// unsigned char flipZero = 0xFE; //0x00
unsigned char dMsg[deM];
int byteArray[7];
int takeByte = 0;
unsigned char *extMsg;
char c;
for(int j = 0; j < 7; j++)
{
if(takeByte == 8)
{
//first letter extracted
takeByte = 0;
}
//byte = msgOne[j];
// byte = img->pixel[j];
//encMsg[j] = byte;
byte = img->pixel[j];
//printf("byte: %c\n", byte);
// printf("byte: %x\n", byte);
byte &= 1;
//printf("byte after: %x\n", byte);
dMsg[j] = byte;
byteArray[j] = byte;
data[j] = byteArray[j];
printf("dMsg:%x ", dMsg[j]);
// printf("pixel:%c \n", img->pixel[j]);
embCount++;
takeByte++;
}
/*
for(int r=0;r<7;r++)
{
printf("\n%d\n", byteArray[r]);
}
printf("count: %d", embCount);
printf("%s ", dMsg);
*/
return decMsg = dMsg;
}
embedding program*******
//////////////////////////////////////////////////////////////
/*
execute as ./emb -i <img2embed> -i <text file> -o <embedIMG>
*/
//////////////////////////////////////////////////////////////
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
int x, y;
unsigned char *pixel;
} PPMImage;
#define RGB_COMPONENT_COLOR 255
static PPMImage *readPPM(const char *filename)
{
FILE * fp;
PPMImage *img;
int rgb_comp_color;
int size = 0;
fp = fopen(filename, "a+");
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
unsigned char *buff;
unsigned char stuff[16];
int c;
int x,y;
buff = (unsigned char*) malloc(sizeof(unsigned char)*size +1);
memset(buff, '\0', sizeof(unsigned char)*size+1);
fgets(stuff, sizeof(stuff), fp);
if (stuff[0] != 'P' || stuff[1] != '3') {
fprintf(stderr, "Invalid image format (must be 'P3')\n");
exit(1);
}
//alloc memory form image
img = (PPMImage*)malloc(sizeof(PPMImage));
if (!img) {
fprintf(stderr, "Unable to allocate memory\n");
exit(1);
}
c = getc(fp);
while (c == '#') {
while (getc(fp) != '\n') ;
c = getc(fp);
}
ungetc(c, fp);
if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) {
fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
exit(1);
}
if (fscanf(fp, "%d", &rgb_comp_color) != 1) {
fprintf(stderr, "Invalid rgb component (error loading '%s')\n", filename);
exit(1);
}
if (rgb_comp_color!= RGB_COMPONENT_COLOR) {
fprintf(stderr, "'%s' does not have 8-bits components\n",filename);
exit(1);
}
//printf("x: %d y: %d\n", img->x, img->y);
unsigned char buffer[1024];
memset(buffer,0,1024);
fgets(buffer,1024,fp);
fread(buff, 1, size, fp);
img->pixel = buff;
/*
for(int h = 0; h < 20; h++)
{
printf("%c", buff2[h]);
}
printf("%s", buff2);
*/
fclose(fp);
return img;
}
void writePPM(const char *filename, unsigned char * img, int x, int y)
{
FILE *fp;
//open file for output
fp = fopen(filename, "wb");
if (!fp) {
fprintf(stderr, "Unable to open file '%s'\n", filename);
exit(1);
}
//write the header file
//image format
fprintf(fp, "P3\n");
//comments
// fprintf(fp, "# Created by %s\n",CREATOR);
//image size
fprintf(fp, "%d %d\n",x,y);
// rgb component depth
fprintf(fp, "%d\n",RGB_COMPONENT_COLOR);
// pixel pixel
fwrite(img,1, strlen(img), fp);
fclose(fp);
}
//unsigned char * embBits(PPMImage *img, int messageLen, unsigned char*msgOne, unsigned char *encMsg)
int embBits(PPMImage *img, int messageLen, unsigned char*msgOne, int embLen)
{
//int count = 2;
int embCount = 0;
int count = 0;
unsigned char *eMsg;
unsigned char byte;
int mask;
unsigned char update;
unsigned char flipOne = 0x01; //0x01
unsigned char flipZero = 0xFE; //0x00
for(int j = 0; j < messageLen; j++)
{
byte = msgOne[j];
//encMsg[j] = byte;
for(int k=7; 0 < k; k--)
{
update = byte;
update = update & (1<<k);
//printf("pixel:%c\n", img->pixel[count]);
//printf("pixel+1:%c\n", img->pixel[count+1]);
// printf("pixel+2:%c\n", img->pixel[count+2]);
if(update == 0)
{
// if i see 1 |=
// if i see a 0 &=
//img->pixel[count] = img->pixel[count] &= flipZero;
img->pixel[count+2] &= flipZero;
}
else
{
//flip bit
//red
//check LSB and FLIP
// img->pixel[count] = img->pixel[count] |= flipOne;
img->pixel[count+2] |= flipOne;
}
//mask--;
//eMsg[count] = img->pixel[count];
//printf("count: %d\n", count);
count = count + 3;
}
// eMsg[j] = byte;
}
//return encMsg = eMsg;
//unsigned char *yes = "sucess";
/*
for(int a = 0; a < messageLen; a++)
{
printf("pixel: %c", img->pixel[a]);
printf("msg: %c\n", eMsg[a]);
// eMsg[a] = img->pixel[a];
}
*/
embCount = count;
return embLen = embCount;
}
int main(int argc, char **argv){
int messageLen;
int i = 0;
PPMImage *img;
int size = 0;
FILE * fp;
int testSize;
fp = fopen(argv[4], "a+");
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
unsigned char *buff;
buff = (unsigned char*) malloc(sizeof(unsigned char)*size +1);
memset(buff, '\0', sizeof(unsigned char)*size+1);
fread(buff, 1, size, fp);
fclose(fp);
// printf("text encryption: %s\n", buff);
testSize = strlen(buff);
// printf("Size of text %d\n", testSize);
messageLen = strlen(buff);
img = readPPM(argv[2]);
/*
int testing = strlen(img->pixel);
for (int f=0;f<6;f++)
{
//f2 = 1
//f3 = 6
printf("%c", img->pixel[f]);
}
*/
// printf("%c \n", img->pixel[2]);
// printf("%c \n", img->pixel[5]);
printf("\n");
// unsigned char * encMsg;
int encMsg = 0;
encMsg = embBits(img, messageLen, buff, encMsg);
// printf("cipher msg:%s\n", img->pixel);
printf("message length: %d\n", messageLen);
// printf("cipher msg length: %d\n", encMsg);
writePPM(argv[6], img->pixel, img->x, img->y);
printf("Please press enter to complete\n");
getchar();
}
I don't know what you are doing specifically with your file and assigning each bit to a position in an array but you can print binary sequences stored in a unsigned int. Try using something like this...
#include <stdio.h>
int main() {
unsigned int arr[] = {00110110, 00111100, 10111011};
int i = sizeof(arr)/sizeof(arr[0]);
while(i-->0) {
printf("%c, ", arr[i]);
}
printf("\n");
}
You can use bit operations to gather these bits into a byte.
#include <stdio.h>
#define BYTE_LENGTH 8
#if 1
/* MSB is in data[0], LSB is in data[BYTE_LENGTH - 1] */
int arrayToChar(const int data[]) {
int c = 0;
int i;
for (i = 0; i < BYTE_LENGTH; i++) {
if (data[i]) c |= (1 << (BYTE_LENGTH - 1 - i));
}
return c;
}
#else
/* LSB is in data[0], MSB is in data[BYTE_LENGTH - 1] */
int arrayToChar(const int data[]) {
int c = 0;
int i;
for (i = 0; i < BYTE_LENGTH; i++) {
if (data[i]) c |= (1 << i);
}
return c;
}
#endif
int main(void) {
int data[8] = {0, 0, 1, 1, 0, 0, 0, 0};
int c = arrayToChar(data);
printf("%d %c\n", c, c);
return 0;
}
If you want to produce one byte from 7 bits, change BYTE_LENGTH to 7.
If you want to deal with long sequence of bits, apply arrayToChar repeatedly with changing the (address of) first element to be passed.

Resources