unsigned char pointer in C#?

2019-09-09 13:57发布

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条回答
仙女界的扛把子
2楼-- · 2019-09-09 14:33

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.

查看更多
祖国的老花朵
3楼-- · 2019-09-09 14:41

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

int noncelen1 = RecvBuffer[5] * 256 + RecvBuffer[6];
查看更多
迷人小祖宗
4楼-- · 2019-09-09 14:43

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.

查看更多
Explosion°爆炸
5楼-- · 2019-09-09 14:55

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?

查看更多
登录 后发表回答