0

I am trying to make a hamming code decoder and encoder in C and I cannot find a way to set the bits of a variable individually.

For example, I am trying to somehow do the following:

#include "stdio.h"

int main () {
    short block = 0010101110001110; // variable to contain the bits to decode
}

Clearly this will not work but I am wondering if there is a way to do this or will I have to define it as the actual number this represents?

Nasser Kessas
  • 359
  • 1
  • 13
  • Do you know how to perform "bitwise OR" and "left shift (<<)"? – Fe2O3 Feb 17 '23 at 04:29
  • Yes, but I am not sure how this will help me assign the variable, only update it after it is already set. What are you suggesting? – Nasser Kessas Feb 17 '23 at 04:31
  • Yes, this involves "composing" the bit pattern in some register... I can't figure out how you plan to create blocks of Hamming codes with a single assignment... – Fe2O3 Feb 17 '23 at 04:40
  • That's not exactly what I was trying to do, I was just trying to temporarily set the value of a variable to a pre-encoded hamming block so I can test a decode function. – Nasser Kessas Feb 19 '23 at 23:34

2 Answers2

1

You can use hexadecimal representation, where each digit represents exactly 4 bits.

unsigned short block = 0x2b8e;
dbush
  • 205,898
  • 23
  • 218
  • 273
1

The next version of C C2x is expected to support binary constants like 0b0010101110001110.

For now, consider hexadecimal constants or perhaps a macro.

Tip: typically such code works best with unsigned types.

#define BIN16U(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) ( \
   ((unsigned)(a)<<15) | ((b)<<14) | ((c)<<13) | ((d)<<12) | \
             ((e)<<11) | ((f)<<10) | ((g)<< 9) | ((h)<< 8) | \
             ((i)<< 7) | ((j)<< 6) | ((k)<< 5) | ((l)<< 4) | \
             ((m)<< 3) | ((n)<< 2) | ((o)<< 1) | ((p)<< 0))

unsigned short block = BIN16U(0,0,1,0, 1,0,1,1, 1,0,0,0, 1,1,1,0);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Nasser Kessas, We could use macro magic to take `M(0010101110001110)` into a hex or octal constant and then extract the bits to form the 16-bit value, but that cleverness is useful only in narrow cases. – chux - Reinstate Monica Feb 17 '23 at 05:13