0

I am trying to perform an exercise in C language whose scope is to encode a message in a 2Q QR-Code via Byte method. This means that a given string should be encoded in a message with:

  • 4 bits for the Mode Indicator (0100 in my case);
  • 8 bits for the length of the message;
  • the message itself (20 characters);
  • 4 null bits as End Of Message signal;
  • 16 bits for 0xEC11 Padding.

I tried using a struct with bit fields like in the folloowing code, but it didn't work out, because the bit order can't be forced.

typedef struct
{
  unsigned char mode   : 4;
  unsigned int length  : 8;
  unsigned char *message;
  unsigned char eof    : 4;
  unsigned int padding : 16;
} code;

I also tried to left shift the bits of the coded message, but once again I received an error message "int value expected", which means (if I understood correctly) I can't shift a struct.

Could anybody suggest an elegant way of performing this task?

Structure
  • 1
  • 2
  • 1
    You can't use bit-fields for the purpose of mapping bits. They are simply too broken by design. Instead, use an array `uint8_t[n]` for storing the data, then parse through it from there. You can have a corresponding struct too if you can reliably disable struct padding on your compiler - otherwise structs won't work without serialize/de-serializing routines. – Lundin Dec 11 '18 at 12:43
  • You need to convert each member separately. [This answer](https://stackoverflow.com/a/47507103/694733) has an one idea to convert data to continuous stream of bits. Minor difference to that answer is that your data members are variable length, and instead of file you would write to output byte array. – user694733 Dec 11 '18 at 12:46
  • As @user694733 says, this is a stream of *bits*, not a stream of *bytes*. Assuming 8 bits/byte, those 4-bit fields in the data really make this a problem - in order to get the *bits* in the right order, you're going to have to account for system endianness in each of the bytes of data. – Andrew Henle Dec 11 '18 at 15:45

1 Answers1

0

I eventually implemented it with data in uint8_t and bit shift. It means I saved the string in an array and than shifted it like in the following:

for(int n_digit = 0; n_digit <= length; n_digit++)
{
    if(n_digit < length)
    {
        *(code + n_digit) = (*(code + n_digit) << 4) + (*(code + n_digit + 1) >> 4);
    }
    else if (n_digit == length)
    {
        *(code + n_digit) = *(code + n_digit) << 4;
    }
}

Perhaps not the highest quality code, but it works just fine.

Structure
  • 1
  • 2