开发者

How can I assign an integer to 3Bytes of field?

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.lengt开发者_如何学ChCIFSPacket = 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.


        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];


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜