tags:

views:

78

answers:

3

Hi,
I have retrieved the Size of my Struct by using size of like below:

int len = Marshal.SizeOf(packet);

Now the len has a Value of 40. I have to assign this 40 to a 3-byte Field of my Structure.My Strucure looks like below:

public struct TCP_CIFS_Packet
        {
           public byte zerobyte;
           public byte[] lengthCIFSPacket;
           public  CIFSPacket cifsPacket;
        }

I tried assigning the values like following:

tcpCIFSPacket.lengthCIFSPacket = new byte[3];
tcpCIFSPacket.lengthCIFSPacket[0] = Convert.ToByte(0);
tcpCIFSPacket.lengthCIFSPacket[1] = Convert.ToByte(0);
tcpCIFSPacket.lengthCIFSPacket[2] = Convert.ToByte(40);

But this doesn't seem to be the right way. Is there any other Way I can do this?

Edit @ho1 and @Rune Grimstad: After using BitConverter.GetBytes like follwoing:

tcpCIFSPacket.lengthCIFSPacket = BitConverter.GetBytes(lengthofPacket);

The size of lengthCIFSPacket changes to 4-bytes but I have only 3-bytes of space for tcpCIFSPacket.lengthCIFSPacket as the packet structure.

Please help.
Thnks,
Subhen

A: 

You can use the BitConverter class to convert an Int32 to an array of bytes using the GetBytes method.

Rune Grimstad
+1  A: 

Look at BitConverter.GetBytes. It'll convert the int to an array of bytes. See here for more info.

ho1
@ho1, I have now tried with tcpCIFSPacket.lengthCIFSPacket=BitConverter.GetBytes(40) which is converting lengthCIFSPacket to 4-bytes but I have only 3-bytes for lengthCIFSPacket.
Subhen
@Subhen: Just ignore the 4th byte and only use the 3 first ones. If you run `GetBytes` on `40` the bytes contain `40.0.0.0` so just ignore the 4th one. Obviously this won't work for too big numbers or for negative numbers, but since you've only got 3 bytes to store it in, you'll have to compromise in some way.
ho1
@Subhen: And if you need to convert it back, just create a byte array with 4 bytes in it, populate the 3 first bytes in it with your 3 bytes and set the 4th to 0 and then use `BitConverter.ToInt32`.
ho1
+2  A: 
        int number = 500000;
        byte[] bytes = new byte[3];
        bytes[0] = (byte)((number & 0xFF) >> 0);
        bytes[1] = (byte)((number & 0xFF00) >> 8);
        bytes[2] = (byte)((number & 0xFF0000) >> 16);

or

        byte[] bytes = BitConverter.GetBytes(number); // this will return 4 bytes of course

edit: you can also do this

        byte[] bytes = BitConverter.GetBytes(number); 
        tcpCIFSPacket.lengthCIFSPacket = new byte[3];
        tcpCIFSPacket.lengthCIFSPacket[0] = bytes[0];
        tcpCIFSPacket.lengthCIFSPacket[1] = bytes[1];
        tcpCIFSPacket.lengthCIFSPacket[2] = bytes[2];
Kikaimaru