0

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;
}
user968000
  • 1,765
  • 3
  • 22
  • 31
  • 2
    Structures with bit fields will still be padded. The simplest way to compress your string data to 5 bits is simply through bitwise operations on an array of unsigned char. – paddy Oct 12 '20 at 22:59
  • _Side note:_ Doing `for(j=0;j – Craig Estey Oct 13 '20 at 02:39
  • Or, better yet, replace the whole loop with: `for (const char *js = str_arr[i]; *js != 0; ++js, ++k) enc_string[k] = *js;` – Craig Estey Oct 13 '20 at 02:45

0 Answers0