Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Bit Packing in C#

Has anyone written a bit packing algorithm in C#  I can do it in C but I'm having trouble in C#.  I want to pack 7 bit characters into octets..  It's called USSD Packing and it's what GSM uses for SMS.

Please post if so!  Thanks

RaZ
Friday, July 09, 2004

If you can do it in C you can do it in C#. The bit manipulation operators are basically the same.

Billy Joel on Software
Sunday, July 11, 2004

Well the code that works in C, when translated to C#, does not work.  I'm keepin with the same operators, just changing the syntax so it conforms.

RaZ
Monday, July 12, 2004

Why don't you post the code? It can't be that long.

Chris Nahr
Monday, July 12, 2004

I'm going to go out on a limb and guess that you're not the author of the C code in question.

Billy Joel on Software
Tuesday, July 13, 2004

Here's the C, assuming input is 160 bytes.

void Encode(char *msg)
{
  int index  = 0;

  for  (int i = 0; i < 20; i++)
  {
      for  (int j = 0; j < 7; j++)
      {
            msg[index] = (msg[i*8+j] >> j) ^ (msg[i*8+j+1] << (7-j));
            index++;
      }
  }
}

Thanks.

RaZ
Tuesday, July 13, 2004

Change "char" to "byte".
In .NET a char is 16 bits wide.

Christopher Wells
Tuesday, July 13, 2004

Assuming the input is 160 bytes is pretty feeble too.

Clutch Cargo
Thursday, July 15, 2004

for  (int i = 0; i < 20; i++)
  {
      for  (int j = 0; j < 7; j++)
      {
            int tmp = i*8+j;  // <------------------
            msg[index] = (msg[tmp] >> j) ^ (msg[tmp+1] << (7-j));
            index++;
      }
  }


And 160 bytes is fine for SMS.

A
Monday, July 19, 2004

--
Assuming the input is 160 bytes is pretty feeble too.

Clutch Cargo
Thursday, July 15, 2004
--

I recommend you read about GSM and SMS before replying.

RAz
Wednesday, July 21, 2004

I recommend you learn how to program a general purpose routine rather than one that's hard coded with magic numbers to do only one specific purpose.

That is pretty much Programming 101.

Clutch Cargo
Wednesday, July 21, 2004

Why do I have the feeling that this code isn't correct. Packing an 8 bit array into a seven bit array will offset by n * 7 / 8, where n is the number of elements in the 8 bit array. So for n = 160 characters as is in the example, the resulting 7 bit array should be 160 * 7 / 8 which is 140 elements. So for every 8 elements in 8 bit arr corresponds 7 elements in 7 bit array. Looking at index++, we see that the index is growing linearly, which is incorrect.

AWZ
Wednesday, September 15, 2004

*  Recent Topics

*  Fog Creek Home