0

In the middle of translating some code from C++ to C#, I found this,

unsigned char *p = m_pRecvBuffer + 5;
unsigned int noncelen1 = *p * 256 + p[1];

How do I translate this into C#? m_pRecvBuffer is a char-array, however I store it as a byte-array.

4 Answers 4

2

Hmm I wonder if some refactoring would be in order for this piece of code. Yes you can use pointers in C#. However, based on that snippet there may be better options. It looks like you're trying to read parts of an incoming stream. Maybe C#'s stream library would work better for this piece of your code?

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

Comments

2

You analyse what the code actually does and translate behaviour, not code. While you could use unsafe methods and pointer arithmetic in c#, this will probably create more problems than it will solve.

2 Comments

Yes, I am aware of this. However, since I know more C# than C++ and cannot debug the code given, the first step for me to wrap my head around this is to get it working in C#, then refactor it into something nice.
ah okay. Same problem for me, I had the idea it was array indexing, but I couldn't put my finger on it.
1

Something akin to

byte[] p = new byte[m_pRecvBuffer.Length - 5];
Array.Copy(m_precvBuffer, p, m_pRecvBuffer.Length - 5);
uint noncelen1 = p[0] * 256 + p[1];

But in that case I don't think you actually need to use an array copy. Just using

uint noncelen1 = p[5] * 256 + p[6];

should be enough, I guess.

3 Comments

I went this route since it resembled code I had already written.
@hokkaido: If you are declaring a new byte array like this and then copying data, this is far less efficient than the answer I posted. There is no reason to be allocating memory or copying arrays.
@Jonathan, note that I say the same. But you don't know how the rest of the code looks. Might be that there's something that only gets a pointer and starts reading from there and maybe refactoring that into array + offset isn't feasible. From the OP's tiny code snippet it's hard to tell.
0

Assuming RecvBuffer is declared as byte[], you would do something like this:

int noncelen1 = RecvBuffer[5] * 256 + RecvBuffer[6];

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.