Compress string using bit field

264 views Asked by At

I have to encode an array of strings such that: 1. The encoded output is a single string with minimum possible length 2. You should be able to decode the string later. String is made up of only lower case characters. I am not very good in using bit fields. . Do i just right shift by 3 when I am assign the letter to enc_string. Or I can use the structure I created? Also how can I make sure that I actually saved space. I cant use sizeof as it returns in bytes?

How do I do the bit packing.

#include <stdio.h>

typedef struct{
    
    int val:5;
    
}input;

char* encode_string(char **str_arr,int len, int *ret_len){
     
    int i = 0;
    int j = 0;
    int k = 0;
    char *enc_string = (char*)malloc(10*len*sizeof(char));
    for(i=0;i<len;i++){
        for(j=0;j<strlen(str_arr[i]); j++){
            enc_string[k] = str_arr[i][j]; // str_arr[i][j]>>3
            k++;
        }
        enc_string[k++] = '*';
        
    }
    if(k>0){
      enc_string[k]='\0';
      *ret_len = k;
    }
    return enc_string;
    
    
}


int main()
{
    char* str[] = {"abcd","fghi","jkl"};
    char *enc_string;
    int enc_len = 0;
    enc_string = encode_string(str,3,&enc_len);
    printf("Encoded string %s size %d \n",enc_string,enc_len);

    return 0;
}
0

There are 0 answers