C# int和byte[]之间的互转

方法1:使用左移和右移

1、int转化为byte[]:

  public  byte[] intToBytes(int value)
        {
            byte[] src = new byte[4];
            src[3] = (byte)((value >> 24) & 0xFF);
            src[2] = (byte)((value >> 16) & 0xFF);
            src[1] = (byte)((value >> 8) & 0xFF);
            src[0] = (byte)(value & 0xFF);
            return src;
        }

2、byte[]转化为int:

public  int bytesToInt(byte[] src, int offset)
        {
            int value;
            value = (int)((src[offset] & 0xFF)
                    | ((src[offset + 1] & 0xFF) << 8)
                    | ((src[offset + 2] & 0xFF) << 16)
                    | ((src[offset + 3] & 0xFF) << 24));
            return value;
        }  

方法2:使用BitConverter

1、int转化为byte[]:

    public  byte[] IntToBitConverter(int num)
        {
            byte[] bytes = BitConverter.GetBytes(num);
            return bytes;
        }

2、byte[]转化为int:

  public  int IntToBitConverter(byte[] bytes)
        {
          int  temp = BitConverter.ToInt32(bytes, 0);
          return temp;
        }

例如:buffer[100],其中 buffer[13]=0,buffer[14]=0 --->合并成int

                                        buffer[15]=0,buffer[16]=1 --->合并成int

                                        buffer[17]=0,buffer[18]=2 --->合并成int

short td1 = BitConverter.ToInt16(new byte[] { buffer[14], buffer[13] }, 0);
short td2 = BitConverter.ToInt16(new byte[] { buffer[16], buffer[15] }, 0);
short td3 = BitConverter.ToInt16(new byte[] { buffer[18], buffer[17] }, 0);

https://blog.csdn.net/qq_30725967/article/details/89145102?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

你可能感兴趣的:(C#)