C#读写文件:十进制转十六进制

写文件有时需要进行进制的转换,下面一个例子是十进制转十六进制,并写入文件。这里用到了进制的转换和C#文件写入的知识。
十进制转十六进制的方法:

    public class HexadecimalConversion      {          public static void WriteBinaryFile(UInt32 data, BinaryWriter fileBinary)//十进制转十六进制          {              byte ch1, ch2, ch3, ch4;                ch1 = Convert.ToByte(data % 256);   //低一位                ch2 = Convert.ToByte((data / 256) % 256);  //低高位                ch3 = Convert.ToByte((data / 256 / 256) % 256); //高一位                ch4 = Convert.ToByte((data / 256 / 256 / 256) % 256); //高高位                fileBinary.Write(ch1);                fileBinary.Write(ch2);                fileBinary.Write(ch3);                fileBinary.Write(ch4);          }      }

 调用转换,并写入文件:

    class Program      {          static void Main(string[] args)          {              string filepath = @"F:\test.my";                UInt32 testData = 100;                FileStream fileStream = null;                BinaryWriter binaryWriter = null;              try              {                  if (!File.Exists(filepath))                  {                      using (File.Create(filepath)) { }                  }                    fileStream = new FileStream(filepath, FileMode.Open);                    binaryWriter = new BinaryWriter(fileStream, System.Text.Encoding.GetEncoding("GBK"));                    fileStream.Seek(0, SeekOrigin.Begin);                    HexadecimalConversion.WriteBinaryFile(testData, binaryWriter);              }              catch              {              }              finally              {                  if (fileStream != null)                  {                      fileStream.Close();                  }                    if (binaryWriter != null)                  {                      binaryWriter.Close();                  }                }          }      }

运行后,用UE打开文件可以看到已经将100转换为十六进制了:
   

 

你可能感兴趣的:(String,C#,null,Class,byte)