2

I would like to hear how you would solve this sort of programming task!? Each type (OPER = 1 type) corresponds to a specific information.

This is just one of about 10 specifications with same structure. A generic way to create those "converters" (protocol) is preferred.

Protocol specification

2 Answers 2

3

If you are reading/writing this, I would simply translate it at the Stream level, somthing like:

int b = source.ReadByte();
if (b < 0) throw new EndOfStreamException();
int operx = b & 15;
int oper = (b >> 4) & 15;            
b = source.ReadByte();
if (b < 0) throw new EndOfStreamException();
int prefix = b & 7;
int reg = (b >> 3) & 31;
b = source.ReadByte();
if (b < 0) throw new EndOfStreamException();
int period = b & 7;
int fas = (b >> 3) & 3;
int tar = (b >> 5) & 7;

If you are doing lots of it, you could wrap it up into something more elegant, perhaps using attributes to specify the offsets - but for 10? meh... not worth it. Writing a robust generic converter is lots of hard work.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank's. Bitwise Shift operators is not really my school, perhaps until now? Though I think I see what this sample gives me. Would you like to give it a short description? 15, 31? I will say that this table is the biggest of about a dousin (with 1-20 options per bit-block)
@dingir 15 decimal is binary 1111, i.e. captures the right-most 4 bits. So looking (for example) at (b >> 4) & 15, this is actually "take the left half of the byte as an integer" - by shifting 4 bits and then taking 4 bits. Likewise, (b >> 3) & 31 allows us to access "reg" - we discard the 3 bites that make up "prefix", and take 5 bits (decimal 31 is binary 11111)
1

If you don't want to mask and shift the bits then you could use the BitVector32 structure. Its CreateSection() method lets you split up to 4 bytes into groups of bits, the indexer then lets you read and write the bit values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.