0

I have a byte that represents two values. First bit represents represents the sequence number. The rest of the bits represent the actual content.

In C, I could easily parse this out by the following:

typedef struct 
{
    byte seqNumber : 1;
    byte content   : 7;
}
MyPacket;

Then I can easily case the input to MyPacket:

char* inputByte = "U"; // binary 01010101
MyPacket * myPacket = (MyPacket*)inputByte;

Then myPacket->seqNumber = 1 myPacket->content = 42

How can I do the same thing in C#?

Thank you kab

Lex L
  • 315
  • 1
  • 3
  • 17
  • possible duplicate of [Bit fields in C#](http://stackoverflow.com/questions/14464/bit-fields-in-c-sharp) – myermian Aug 26 '14 at 00:21
  • Thanks m-y! It looks like a good method. I will work on that method when I get some time, but for now, I will use the method proposed by Jon Jay – Lex L Aug 26 '14 at 14:30

1 Answers1

0

I would just use properties. Make getters and setters for the two parts that modify the appropriate bits in the true representation.

class myPacket {
  public byte packed = 0;
  public int seqNumber {
    get { return value >> 7; }
    set { packed = value << 7 | packed & ~(1 << 7); } 
  }
  public int content {
    get { return value & ~(1 << 7); }
    set { packed = packed & (1 << 7) | value & ~(1 << 7); } 
  }
}

C# likes to keep its types simple, so I am betting this is the closest you are getting. Obviously it does not net you the performance improvement in C, but it salvages the meanings.

  • This is a good idea. For the get property for seqNumber, i am using (packed >> 0) & 1 For the get property for content, i am using (packed >> 1) & 127 – Lex L Aug 26 '14 at 14:31
  • That puts the bits in the opposite order you claimed, no? I am used to a world where the first bit is most-significant. Also, surely the (packed >> 0) is unnecessary, as that does nothing. – Jon Jay Obermark Aug 26 '14 at 19:27
  • C++ uses Big-Endian order, so the seqNumber will have the least significant bit (starting from the right) To get that, I have to use (packed >> 0) & 1 I think that's how it works. Let me know if you find otherwise. Thanks! – Lex L Aug 26 '14 at 19:42
  • (packed & 1) would do as well, it chooses the low-order bit of the variable packed. – Jon Jay Obermark Aug 26 '14 at 19:58