6

What is the best way to handle the following situation in C#?

I have a server application written in C/C++.

For example It creates a unsigned char buffer with length 256. In this buffer the server stores the data the client sends to it. After storing, there are some cryptography checks with the received buffer.

I'm writing a client for this server in C#.

The problem is the buffer the server is expecting at fixed length of 256.

When I create a byte[] array with content and total length of 256 the cryptography checks are failing.

The reason I found out is simple. The server expects a buffer of 256 bytes long. For example if the message is "Hello World", the rest of the buffer has to be 0-padded. Or, better explained: the bytes need to be (unsigned) "204" or (signed) "-52".

I think this is a C/C++ concept issue/problem.

To solve my problem, I am setting that value explicitly.

public static byte[] GetCBuffer(this byte[] data, int len)
{
    byte[] tmp = new byte[len];
    for(int i = 0; i < len; i++)
        if(i < data.Length)
            tmp[i] = data[i];
        else
            tmp[i] = 204;
    return tmp;
}

Are there better ways to work with these art expected bytes? Am I not seeing something essential?

Varaquilex
  • 3,447
  • 7
  • 40
  • 60
my2cents
  • 103
  • 5
  • Based on this [answer](http://stackoverflow.com/a/6150310/2145211) to _Initialize a byte array to a certain value, other than the default null?_ I would say your solution is a good one. – Harrison Nov 04 '13 at 18:48
  • I would generalize further and pass in the "blank" value, so you could reuse again without modification if the value is something other than 204. – Adam V Nov 04 '13 at 18:56

2 Answers2

2

If you don't like if in your code, you can try LINQ:

public static byte[] GetCBuffer(this byte[] data, int len)
{
    byte[] tmp = Enumerable.Repeat((byte)204, len).ToArray();
    for(int i = 0; i < data.Length; i++)
    {
      tmp[i] = data[i];
    }

    return ret;
}

But conceptually, it's the same, just looks (arguably) a bit nicer.

undefined
  • 1,354
  • 1
  • 8
  • 19
1

Can you 'memset' the entire array to the desired fill character and then insert the actual data?

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • 1
    That sounds like a more readable result, plus you can `Buffer.BlockCopy` the data after clearing it. – C.Evenhuis Nov 04 '13 at 18:53
  • Can you specify your idea? How to implement memset without pinvoke overhead? In fact, i already trye'd BlockCopy before. But the elements than are 0 filled. Whitch will fail at the server side when the elements are treated. – my2cents Nov 04 '13 at 20:16
  • Your post stated this: "I have a server application written in C/C++. ... it creates a unsigned char buffer with length 256." So I assumed it was C/C++ and it needed to be done when the array was created. – Steve Wellens Nov 05 '13 at 02:12