我要把int类型的变量的值(占据4个字节)转到4个字节的byte[]里,怎么办?(不想用unsafe指针)

解决方案 »

  1.   

    转换成int[32]  的101001....01010数组
    再转成每8位的值
      

  2.   

    Dim i As Integer = 12
            Dim bytes(4) As Byte
            bytes = System.Text.Encoding.Unicode.GetBytes(i)
      

  3.   

    System.Text.Encoding.Unicode好象没有GetBytes(int)这个方法吧。:(
    如果是double怎么办呢?(C#里是不能象VB.NET里这样转换的)
      

  4.   

    Use "BitConverter.GetBytes" method to convert int value or long value to bytes.
      

  5.   

    It's also applied to convert double to bytes.
      

  6.   

    我做了这么个小函数:byte []MyConvert(long Value)
    {
     byte []byteResult;
     string strResult = Value.ToString("");  //转换成十六进制字符串 if(strResult % 2 != 0) strResult = "0" + strResult; //把字符串长确定为2的整数倍
     byteResult = new byte[strReslut.Length];
     for(int i=0;i<byteResult.Length;++i)
     {
      byteResult[i] = Convert.ToByte(strResult.SubString(2*i, 2));
     } return byteResult;
    }//相信对其它int/double都可以工作。
      

  7.   

    string strResult = Value.ToString("X");  //转换成十六进制字符串,少写了一个X
      

  8.   

    if(strResult.Length % 2 != 0) strResult = "0" + strResult; //少写了一个Length